skip to content

Arrays

Java arrays: how you declare and create them, the fixed length, jagged multidimensional forms, covariance, and the Arrays and System helpers. Interviewers use arrays to contrast with generics and with ArrayList.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 1 of 2

What happens in Java when you access an array element with an index that is outside the array's valid range?

level: juniorimportance: must knowfreq 70%

answer

  1. 0 to length - 1
  2. AIOOBE = unchecked RuntimeException
  3. off-by-one: i <= length
  4. no silent corruption like C
  5. empty array has no valid index

basics

~10 s

Java checks every array access at runtime. If the index is below 0 or at/above the array's length, it throws an ArrayIndexOutOfBoundsException instead of reading wrong memory.

solid answer

~40 s

Every time you read or write an array element in Java, the JVM verifies at runtime that the index is in the range 0 to length-1. If it is negative or greater than or equal to the array's length, the JVM throws an ArrayIndexOutOfBoundsException (a subclass of RuntimeException, so it is unchecked). The valid indices are always 0-based, and the highest legal index is length - 1. A classic off-by-one bug is looping with i <= array.length instead of i < array.length, which accesses one past the end. This guarantee means Java never silently reads or corrupts adjacent memory the way C does; an out-of-bounds access always fails loudly and deterministically with an exception that names the bad index.

go deeper

for a junior

Knows access uses 0-based indices, the last valid index is length - 1, and a bad index throws ArrayIndexOutOfBoundsException rather than corrupting memory.

for a middle

Explains the half-open range 0 <= i < length, recognizes the off-by-one loop bug, and knows the exception is unchecked (RuntimeException).

for a senior

Frames bounds checking as Java's memory-safety guarantee, contrasts it with C's undefined behavior, and notes the exception message now includes index and length.

for a principal

Discusses the safety-vs-performance trade-off the check represents and why eliminating the entire buffer-overflow vulnerability class is worth a runtime cost the JIT can usually remove.

## What an array is An **array** in Java is a fixed-size, contiguous block of memory holding elements of the same type, accessed by a numeric **index**. Indices are **0-based**: the first element is at index `0`, and for an array of `n` elements the last element is at index `n - 1`. The number of slots is exposed by the `.length` field. ## What 'bounds checking' means **Bounds checking** is the act of verifying, *before* an access actually touches memory, that the requested index falls inside the valid range. The valid range is: ``` 0 <= index < array.length ``` Java performs this check **automatically at runtime on every single array access** — both reads (`a[i]`) and writes (`a[i] = x`). This is part of the language's memory-safety guarantee and you cannot turn it off. ## What happens on a bad index If the index is **negative** (e.g. `-1`) or **too large** (`>= length`), the JVM does not read or write the memory. Instead it throws an **`ArrayIndexOutOfBoundsException`** (often abbreviated AIOOBE). This class extends `IndexOutOfBoundsException`, which extends `RuntimeException`, so it is an **unchecked exception** — you are not forced to declare or catch it. Modern JVMs include the offending index and the array length in the message, e.g. `Index 5 out of bounds for length 5`. ## Why this matters — contrast with C In languages like **C**, an out-of-bounds access is *undefined behavior*: the program might read garbage, silently corrupt a neighboring variable, or crash unpredictably. This is a major source of security holes (buffer overflows). Java's mandatory bounds check converts that whole class of bug into a **deterministic, loud, debuggable exception**, which is why Java is called a **memory-safe** language for arrays. ## The classic off-by-one bug The most common cause is the **fence-post / off-by-one** error: ```java int[] a = new int[5]; // valid indices 0..4 for (int i = 0; i <= a.length; i++) { // BUG: i reaches 5 System.out.println(a[i]); // a[5] -> AIOOBE } ``` The fix is the half-open convention `i < a.length`. Other triggers: an empty array (length 0 has *no* valid index, so even `a[0]` throws), or using a negative computed index. ## Key takeaways - Valid range is always `0` to `length - 1`. - The check happens on *every* access, automatically, at runtime. - The failure is an unchecked `ArrayIndexOutOfBoundsException`, not silent corruption. - Empty arrays have no valid index at all.

  • Is ArrayIndexOutOfBoundsException checked or unchecked, and what does that imply?
    Unchecked — it extends RuntimeException via IndexOutOfBoundsException, so the compiler does not force you to catch or declare it. It signals a programming bug, so the right fix is correct index logic rather than routinely catching it.
  • What index throws on an empty (length 0) array?
    Any index does — there are no valid indices. Even a[0] throws AIOOBE because 0 is not less than length 0.

saying these in an interview costs you the question

  • Saying the program returns null or 0 for a bad index (it throws an exception, not a default value)
  • Claiming the exception is checked and must be declared with throws
  • Thinking the last valid index is length, not length - 1
  • Assuming Java reads adjacent memory like C on overflow

context

open as a page

Why is a Java array fixed-length once created, and how do you handle a collection that needs to grow?

level: juniorimportance: must knowfreq 60%

basics

~20 s

An array's length is set when you create it and can never change. To grow, you either create a bigger array and copy the elements over, or use a class like ArrayList that does that copying for you.

open as a page

What are the ways to declare an array variable in Java, and is there a difference between int[] a and int a[]?

level: juniorimportance: must knowfreq 70%

basics

~20 s

You can write the brackets after the type, like int[] a, or after the variable name, like int a[]. Both declare an array of ints and behave identically. The first style is preferred in Java.

open as a page

How do you get the size of an array in Java, and why is it a field rather than a method?

level: juniorimportance: must knowfreq 68%

basics

~10 s

You read the public length field, like a.length (no parentheses). It tells you how many elements the array has. It is fixed for the array's lifetime and you cannot change it.

open as a page

How do you create (instantiate) an array in Java with the new keyword, and what does the size argument do?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Use new with the element type and a length, like new int[5]. This allocates an array of 5 ints on the heap. The length is fixed for the array's lifetime, and you fill the slots by index afterwards.

open as a page

What is java.util.Arrays, and what kinds of operations does it provide for working with arrays?

level: juniorimportance: must knowfreq 60%

basics

~20 s

java.util.Arrays is a helper class full of static methods for arrays: it can sort, search, fill, copy, compare, print, and turn an array into a list or stream. You call them like Arrays.sort(a) without creating an Arrays object.

open as a page

What is the fundamental difference between a Java array and an ArrayList, and when would you choose one over the other?

level: juniorimportance: must knowfreq 80%

basics

~20 s

An array has a fixed size set when you create it and can hold primitives or objects. An ArrayList grows and shrinks automatically and only holds objects. Use an array for a known fixed count; use an ArrayList when the size changes.

open as a page

In Java, what is a two-dimensional array really, and why does Java have no true rectangular multidimensional arrays?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A Java 2D array is an array whose elements are themselves arrays (an array of arrays). Java has no single block of rows-by-columns; each row is a separate array object, so rows can even have different lengths.

open as a page

What is System.arraycopy and what do its five parameters mean?

level: juniorimportance: must knowfreq 55%

basics

~10 s

System.arraycopy copies a range of elements from one array to another. You pass the source array, where to start reading, the destination array, where to start writing, and how many elements to copy.

open as a page

What is ArrayStoreException and when exactly is it thrown?

level: middleimportance: must knowfreq 62%

basics

~20 s

ArrayStoreException is a runtime error thrown when you try to store an element into an array whose real component type can't hold it — for example storing an Integer into a String[] that you accessed through an Object[] reference.

open as a page

When you create an array with new, what initial values do its elements hold?

level: middleimportance: must knowfreq 65%

basics

~10 s

Every element is automatically set to a default: 0 for numbers, false for boolean, the null character for char, and null for objects. So new int[3] is [0,0,0] and new String[3] is three nulls.

open as a page

How does Arrays.binarySearch work, what precondition must hold, and what does it return when the key is absent?

level: middleimportance: must knowfreq 65%

basics

~20 s

Arrays.binarySearch quickly finds a value in a sorted array. The array MUST already be sorted, or results are wrong. If found, it returns the index. If not found, it returns a negative number: -(insertionPoint) - 1.

open as a page

Why are Java generics invariant when arrays are covariant, and what practical difference does that make?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Generics are invariant: List<String> is not a List<Object>, so a bad store is caught at compile time. Arrays are covariant, so the same kind of bad store compiles and only fails at runtime with ArrayStoreException.

open as a page

What are the pitfalls of Arrays.asList — its fixed-size backing behavior and how it handles a primitive array?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Arrays.asList wraps an array as a List, but it's a fixed-size view backed by the array: you can't add or remove (those throw), and changes write through to the array. Also, asList(int[]) gives a List<int[]> with one element, not a List<Integer>; use a boxed Integer[] or a stream.

open as a page

What does it mean that Java arrays are covariant, and why is String[] assignable to Object[]?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Covariance means that if String is a subtype of Object, then String[] is treated as a subtype of Object[]. So you can assign a String[] to an Object[] variable and Java accepts it at compile time.

open as a page

How does Java handle partial allocation and default initialization across the dimensions of a multidimensional array?

level: juniorimportance: should knowfreq 40%

basics

~20 s

new int[3][4] allocates every level and fills all cells with 0. new int[3][] allocates only the outer array, leaving each row null until you assign it. You may leave trailing dimensions empty but not skip an earlier one.

open as a page

Why is catching ArrayIndexOutOfBoundsException usually a code smell, and what should you do instead?

level: middleimportance: should knowfreq 40%

basics

~20 s

An out-of-bounds exception almost always means a bug in your index logic, not a normal situation. So instead of catching it, fix the loop or validate the index up front so the bad access never happens.

open as a page

What is the array initializer shorthand in Java, and when can you use the curly-brace form?

level: middleimportance: should knowfreq 60%

basics

~20 s

You can create and fill an array in one step with braces, like int[] a = {1, 2, 3};. The length comes from the number of values. The bare {1,2,3} form only works at declaration; elsewhere you must write new int[]{1,2,3}.

open as a page

How do Arrays.copyOf and Arrays.copyOfRange work, what happens at the boundaries, and is the copy deep or shallow?

level: middleimportance: should knowfreq 45%

basics

~20 s

Arrays.copyOf makes a new array of a chosen length, copying the original and padding with defaults (0/null/false) if longer, or cutting off if shorter. copyOfRange copies a slice [from, to). Both make a shallow copy: object elements are shared, not cloned.

open as a page

What is the difference between Arrays.equals and Arrays.deepEquals (and likewise toString vs deepToString), and when must you use the deep version?

level: middleimportance: should knowfreq 50%

basics

~20 s

Arrays.equals compares two arrays one element at a time, but for arrays of arrays it only checks if the inner arrays are the same object. Arrays.deepEquals goes inside nested arrays and compares their contents too. Same idea for toString (one level) vs deepToString (nested).

open as a page

What are the common pitfalls when converting between arrays and Lists in Java (Arrays.asList, toArray, primitive arrays)?

level: middleimportance: should knowfreq 50%

basics

~20 s

Arrays.asList gives a fixed-size list backed by the array, so add/remove throws and changes write through to the array. Passing a primitive array like int[] to asList makes a one-element List of the array, not a list of ints. To get a real resizable list, wrap it: new ArrayList<>(Arrays.asList(...)).

open as a page

Compare the performance characteristics of common operations (random access, append, insert/remove in the middle, contains) for arrays and ArrayList. What does ArrayList's add() being 'amortized O(1)' mean?

level: middleimportance: should knowfreq 55%

basics

~20 s

Both give O(1) access by index. Appending to an ArrayList is usually O(1) but occasionally has to grow and copy everything, which is slow; averaged out it's still cheap ('amortized O(1)'). Inserting or removing in the middle is O(n) for both because elements must shift. Searching by value (contains) is O(n).

open as a page

Why does storing many int values in an ArrayList<Integer> cost more memory and CPU than an int[], and how big is the difference?

level: middleimportance: should knowfreq 60%

basics

~20 s

An int[] stores raw numbers packed together. An ArrayList<Integer> must wrap each int in an Integer object, which adds object overhead and an extra pointer per element, and costs CPU for boxing and unboxing. So it uses several times more memory and is slower.

open as a page

How should you correctly iterate over a multidimensional or jagged array in Java, and what bugs arise from doing it wrong?

level: middleimportance: should knowfreq 45%

basics

~10 s

Loop the outer array with a.length, and for each row loop with that row's own a[i].length. Using a single fixed width or assuming rows are non-null causes out-of-bounds errors or NullPointerExceptions.

open as a page

What is a jagged (ragged) array in Java, and how do you create one with rows of differing length?

level: middleimportance: should knowfreq 55%

basics

~10 s

A jagged array is a 2D array whose rows have different lengths. Because Java's 2D arrays are arrays of arrays, you just create the outer array first, then assign each row its own length.

open as a page

How does Arrays.copyOf relate to System.arraycopy, and when would you use each?

level: middleimportance: should knowfreq 48%

basics

~20 s

Arrays.copyOf allocates a brand-new array of the size you ask for and uses System.arraycopy internally to fill it. Use copyOf when you want a fresh array; use arraycopy when you already have the destination and want to copy into a specific spot.

open as a page

What is the runtime cost of array bounds checks, and how does the JIT compiler optimize them away?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Each array access includes a tiny check that the index is valid, which costs a compare-and-branch. The JIT compiler often proves the index is always safe (for example in a normal for loop) and removes the check, so well-written loops pay almost nothing.

open as a page

How does Arrays.sort behave for primitives vs objects (algorithm, stability, custom order), and what does Arrays.stream / parallelSort add?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Arrays.sort orders an array ascending in place. For objects it's a stable merge-style sort and you can pass a Comparator for custom order; for primitives it's an unstable quicksort and there's no comparator. Arrays.stream turns an array into a stream for map/filter/reduce; parallelSort sorts using multiple threads.

open as a page

Explain array covariance versus generics invariance: why does Object[] arr = new String[1]; arr[0] = 1; compile but throw at runtime, while the List equivalent won't compile?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Arrays are covariant: a String[] can be used as an Object[], so storing the wrong type compiles but fails at runtime with ArrayStoreException. Generics are invariant: a List<String> is not a List<Object>, so the bad assignment is caught by the compiler instead.

open as a page

Compared with a flat one-dimensional array, what are the memory-layout and performance characteristics of Java's array-of-arrays, and when would you flatten?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Java's 2D array scatters each row as a separate heap object, so reaching an element needs an extra pointer hop and gives worse cache locality. For hot numeric code you can flatten to one 1D array and index as data[i*cols+j] for contiguous, cache-friendly access.

open as a page

showing 1–30 of 35