Syntax
type[] arrayName = new type[size];Examples
Creating and Accessing Arrays
Declaring arrays with initial values and reading elements by index.
int[] numbers = {10, 20, 30, 40, 50};
String[] names = new String[3];
names[0] = "John";
names[1] = "Zain";
names[2] = "Jamal";
System.out.println(numbers[0]); // 10
System.out.println(numbers.length); // 5
System.out.println(names[1]); // ZainIterating Over an Array
Looping through array elements with a standard for loop or an enhanced for-each loop.
int[] scores = {85, 92, 78, 90};
for (int i = 0; i < scores.length; i++) {
System.out.println("Index " + i + ": " + scores[i]);
}
// Enhanced for-each loop - simpler when you don't need the index
for (int score : scores) {
System.out.println(score);
}Multi-Dimensional Arrays
Creating and accessing a 2D array, commonly used to represent grids or matrices.
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(grid[1][2]); // 6 (row 1, column 2)
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}Common Array Operations with java.util.Arrays
Using the built-in Arrays utility class for sorting, filling, and printing.
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9]
int[] filled = new int[5];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled)); // [7, 7, 7, 7, 7]Best practices
- Use an ArrayList instead of a plain array whenever the collection needs to grow or shrink dynamically
- Use the enhanced for-each loop when you just need the values, and a standard indexed loop when you need the index too
- Use Arrays.toString() (or Arrays.deepToString() for 2D arrays) to print array contents readably - printing an array directly shows its memory reference, not its contents
- Always check array.length before accessing an index in a loop to avoid an ArrayIndexOutOfBoundsException
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification