4.1 Arrays and Indexes
An array stores multiple values of the same type in one ordered block. Java array indexes start at 0.
int[] scores = {88, 91, 76, 95, 83};
System.out.println(scores[0]); // 88
System.out.println(scores[4]); // 83An array of length 5 has valid indexes from 0 through 4. Java protects arrays at runtime: if you read scores[5], the program throws an ArrayIndexOutOfBoundsException instead of silently reading random memory.
Declaring arrays
The most common Java style puts the brackets after the type:
int[] values;
double[] temperatures;
String[] names;You can create an array with literal values:
int[] scores = {88, 91, 76, 95, 83};Or create a fixed-size array first, then fill it:
int[] counts = new int[4];
counts[0] = 12;
counts[1] = 9;
counts[2] = 15;
counts[3] = 6;The size of a Java array is fixed after creation. new int[4] creates exactly four slots. You can change the values inside the slots, but you cannot make that same array longer.
Default values
When Java creates a new array, every slot gets a default value:
- Numeric arrays start with
0or0.0.
boolean[]starts withfalse.
char[]starts with the null character'\0'.
- Object arrays such as
String[]start withnull.
int[] counts = new int[3];
System.out.println(counts[0]); // 0Array length
Arrays use the field .length, not a method call:
int[] scores = {88, 91, 76, 95, 83};
System.out.println(scores.length); // 5Notice the difference:
- Array length:
scores.length
- String length:
name.length()
This difference feels small, but it matters. Arrays expose a length field; strings provide a length() method.
Processing arrays with loops
Arrays are often processed with loops:
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}The loop condition uses < scores.length, not <= scores.length, because the last legal index is scores.length - 1.
If you only need values and not indexes, use the enhanced for loop:
for (int score : scores) {
System.out.println(score);
}Use the index loop when you need to update an element or refer to its position. Use the enhanced for loop when you only need to read values.