AP® Computer Science A · Unit 4 · Topic 4.3
Default Values and ArrayIndexOutOfBoundsException
When you create an array with new, Java fills every slot with a default value based on the element type before you store anything. Try to read or write past the last valid index and Java throws ArrayIndexOutOfBoundsException instead of growing the array.
An array is a fixed block of memory, sized the moment you call new. Java does not leave that memory blank or garbage-filled. It walks through every slot and writes a default value matching the element type, so the array is never in an undefined state. Numeric types default to zero: int arrays get 0, double arrays get 0.0. Boolean arrays get false. Arrays of any reference type, like String, Integer objects, or your own classes, get null, because no object has been built and placed there yet.
This matters most when you loop. A common pattern writes to a[i] while i runs from 0 up to a.length - 1. Picture int[] a = new int[5]. Valid indices are 0, 1, 2, 3, 4. If your loop condition is wrong and lets i reach 5, Java throws ArrayIndexOutOfBoundsException the moment you try a[5], because that memory was never allocated. Java will not quietly stretch the array to fit — length is locked in forever at creation, by design, so a bug that silently corrupts memory becomes a loud, immediate crash instead.
This connects directly to ArrayLists later in the unit, which can grow because they manage a hidden array behind the scenes and replace it with a bigger one when needed. Arrays never do that themselves. Knowing the default values also matters for tracing code: a method that returns an array of counts or flags without writing every slot will still print valid numbers, zeros and falses, not errors, which can hide a logic bug.
Key terms
- default value
- The value Java automatically stores in every array slot at creation: 0 for numbers, false for boolean, null for reference types.
- ArrayIndexOutOfBoundsException
- The error Java throws when code accesses an array index less than 0 or greater than or equal to its length.
- length
- The fixed number of slots an array has, set permanently when the array is created with new.
- null
- The default value for reference-type array elements, meaning the slot points to no object.
Watch it explained
- How it worksHow does new fill an array with the default value belonging to its element type?
- Worked exampleFind what new int[3], new double[3], new boolean[3], and new String[3] hold at creation.
- Worked exampleTrace a loop writing to a[i] with i running up to a.length and find the failing pass.
- Common mistakeWhy doesn't Java quietly grow an array when you index one past the end?
Check yourself
End of topic.