How to Declare and Initialize an Array in Java
Java arrays are fixed-length containers for a single type. Declare one with int[] a = new int[5]; (five zeroes) or int[] a = {1, 2, 3}; (initialised inline). The size cannot change after creation.
Declaration forms
// Form 1: declare then initialize (fixed size, default values)
int[] scores = new int[5]; // [0, 0, 0, 0, 0]
boolean[] flags = new boolean[3]; // [false, false, false]
String[] names = new String[4]; // [null, null, null, null]
// Form 2: declare and fill inline (array initializer)
int[] primes = {2, 3, 5, 7, 11};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
// Form 3: new keyword with values (useful when not declaring at the same time)
int[] more = new int[]{10, 20, 30};
passTo(new String[]{"a", "b"}); // anonymous array in method call
Accessing elements
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]); // 10 (first element)
System.out.println(arr[4]); // 50 (last element)
System.out.println(arr.length); // 5
arr[2] = 99; // modify element at index 2
// arr is now {10, 20, 99, 40, 50}
Accessing an index that is out of range throws ArrayIndexOutOfBoundsException. Valid indices are 0 to arr.length - 1.
Multi-dimensional arrays
// 2D array (3 rows × 4 columns):
int[][] grid = new int[3][4];
grid[0][0] = 1;
// Inline 2D:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6
// Jagged array (rows of different lengths):
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};
Array of objects
Person[] team = new Person[3];
team[0] = new Person("Ada", 36);
team[1] = new Person("Grace", 85);
team[2] = new Person("Linus", 54);
// Or inline:
Person[] team2 = {
new Person("Ada", 36),
new Person("Grace", 85)
};
Iterating an array
String[] colors = {"red", "green", "blue"};
// Enhanced for loop (read-only):
for (String color : colors) {
System.out.println(color);
}
// Traditional loop (when you need the index):
for (int i = 0; i < colors.length; i++) {
System.out.println(i + ": " + colors[i]);
}
When to use ArrayList instead
If you do not know the size ahead of time, or need to add/remove elements, use ArrayList<T>. Arrays are the right choice when the size is fixed and performance is critical (arrays have slightly less overhead than ArrayList).