skip to content

Array Bounds Checking

Every index is checked at runtime, throwing ArrayIndexOutOfBoundsException, and the JIT eliminates many of those checks when it can prove them redundant. Interviewers use it to contrast Java's safety with C-style buffer overruns.

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

questions

5

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

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 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 do bounds checks work for multidimensional arrays, and what role does this safety guarantee play in the JVM's overall memory-safety model?

level: principalimportance: nice to knowfreq 25%

basics

~20 s

A 2D array in Java is really an array of arrays, so each level is bounds-checked separately. This per-access checking is part of why the JVM is memory-safe: no Java code can read or write outside an allocated object's bounds.

open as a page