Java Notes
An array stores a fixed number of values of one element type. Learn creation, indexing, length, default values, and safe access in Java.
An array stores multiple values of one element type under one name. Each value has an index, beginning at 0. Arrays are useful when you know the number of values in advance, such as marks for 30 students or temperatures for seven days.
Create and access an array
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
marks[0] is the first element, not the second. For an array of length 4, valid indexes are 0, 1, 2, and 3.
Declaration, creation, and initialization
These are separate steps:
When the values are already known, use an array initializer instead:
String[] days = {"Monday", "Tuesday", "Wednesday"};The preferred declaration style is int[] scores, because the [] stays with the type. Java also accepts int scores[], but avoid it in new code.
Fixed size and default values
An array's length is fixed when it is created. You can change an element, but you cannot add a fourth element to new int[3].
| Array type | Default value for a new element |
|---|---|
int[], long[], double[] | 0, 0L, 0.0 |
boolean[] | false |
char[] | \u0000 |
String[] and other object arrays | null |
Do not confuse this with a local variable: Java requires local variables to be explicitly initialised before you read them.
Traverse every element
Use an enhanced for loop when you only need each value:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Use an indexed for loop when you need the position or need to replace values.
Bounds and common errors
An invalid index throws ArrayIndexOutOfBoundsException at runtime:
The safe last index is always array.length - 1. For an empty array, there is no valid index, so check array.length > 0 before reading its first or last element.
What to remember
- Arrays have a fixed length and use zero-based indexes.
- An array is an object; an array variable refers to that object.
array.lengthis a field, not a method: writelength, notlength().- Use an enhanced
forloop to read all values and an indexed loop when position matters.
Continue the lesson path