An array stores an ordered group of values of the same type. Every element is accessed by index. A Java array has a fixed length after creation and does not provide append, insert, or pop.
Creating arrays
Use an array initializer when the values are known. new int[n] creates n slots first. The element type comes before the variable name, and brackets mean “a group of this type.”
int[] scores = {88, 91, 76, 95, 83};
int[] counts = new int[4];
counts[0] = 12;
counts[1] = 9;New arrays receive default values: numeric values are 0, boolean is false, char is the null character, and object references such as String are null. The slot count is decided when the array is created.
KNOWLEDGE QUIZ
Accessing array elements
Array indexes start at 0, so the first element is scores[0]. An array of length 5 has indexes 0 through 4. Accessing scores[5] throws ArrayIndexOutOfBoundsException.
int[] scores = {88, 91, 76, 95, 83};
System.out.println(scores[0]); // 88
System.out.println(scores[4]); // 83
scores[2] = 80;
System.out.println(scores[2]); // 80Array index spotlight
Select any slot and let a Java expression point to exactly one value. Valid indexes always run from 0 through scores.length - 1.
KNOWLEDGE QUIZ
Array length and loops
Arrays use the length field without parentheses. The last valid index is array.length - 1. Use an index loop when positions matter and an enhanced for loop when only values matter.
for (int i = 0; i < scores.length; i++) {
System.out.printf("scores[%d] = %d%n", i, scores[i]);
}
for (int score : scores) {
System.out.println(score);
}KNOWLEDGE QUIZ
Fixed length and common operations
You can rewrite existing elements and search with a loop. Neither action adds or removes slots.
int[] values = {4, 0, 7, 0, 2, 9};
values[2] = 5;
for (int value : values) {
System.out.print(value + " ");
}KNOWLEDGE QUIZ
Move zeroes to the end of an array
- Scan every element with a read index.
- Use a write index for the next nonzero destination.
- Fill the remaining cells with zero after the scan.
Reverse an integer array in place
Use two indexes, left and right, moving inward while swapping values. Transform {2, 4, 6, 8, 10} into {10, 8, 6, 4, 2}.
- Point left at the first element and right at the last.
- Swap both ends, then move both indexes inward.
- Stop when left is no longer less than right and print the array.