Arrays
An array is a fixed-size container that holds multiple values of the same type in a single
variable. Instead of creating num1, num2, num3, ... you create one
array and access each value by its index.
Declaring and Initializing an Array
You can declare an array and fill it with values right away using curly braces, or create it with
new and a fixed size (its elements start at a default value, 0 for numeric types).
int[] nums = {1, 2, 3}; // declared and initialized together
int[] scores = new int[5]; // an array of 5 ints, all default to 0
Accessing and Modifying Elements
Array indexes start at 0, so the first element is arr[0] and the last is arr[arr.length - 1].
int[] nums = {10, 20, 30};
System.out.println(nums[0]); // 10, the first element
nums[1] = 99; // modify the second element
System.out.println(nums[1]); // 99
The .length Property
An array's size is available through .length. It's a property, not a method —
there's no parentheses. Writing nums.length() is a common beginner mistake that won't compile
(that syntax is for String.length(), which really is a method).
int[] nums = {10, 20, 30};
System.out.println(nums.length); // 3 -- correct, no parentheses
// nums.length(); // compile error - length is not a method here
Iterating an Array
A regular for loop gives you the index; the enhanced for-each loop gives you each value directly.
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
System.out.println("Index " + i + ": " + nums[i]);
}
for (int n : nums) {
System.out.println(n);
}
2D Arrays
A 2D array is an array of arrays — useful for grids, matrices, or tables of data. You traverse it with nested loops.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
// 1 2 3
// 4 5 6
Watch Out: ArrayIndexOutOfBoundsException
Accessing an index that doesn't exist — negative, or equal to/greater than the array's length —
throws ArrayIndexOutOfBoundsException at runtime. The compiler won't catch this for you.
int[] nums = {10, 20, 30};
System.out.println(nums[3]); // throws ArrayIndexOutOfBoundsException - valid indexes are 0-2
i < array.length (never <=) to avoid stepping one index past the end of the array.