Java Arrays: Single Dimensional and Multi-Dimensional Arrays

An array in Java is a container object that holds a fixed number of values of the same type. Arrays are one of the most fundamental data structures, letting you store and access multiple related values using a single variable name and an index.

Single-Dimensional Arrays

A single-dimensional array is a simple list of elements, all of the same type, stored in contiguous memory and accessed using a zero-based index.

Declaring and Initializing

int[] numbers = new int[5]; // declares an array of 5 ints
int[] scores = {90, 85, 77, 92, 60}; // declared with values directly

Accessing Array Elements

System.out.println(scores[0]); // 90
scores[2] = 100; // update the third element

Iterating Over an Array

for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

for (int s : scores) {
    System.out.println(s);
}

Multi-Dimensional Arrays

A multi-dimensional array is essentially an array of arrays, most commonly used as a two-dimensional array to represent tables, grids, or matrices.

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Accessing Multi-Dimensional Array Elements

System.out.println(matrix[1][2]); // 6 (row 1, column 2)

Iterating Over a 2D Array

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

Jagged Arrays

Java also supports jagged arrays, where each row of a multi-dimensional array can have a different length, unlike a strict rectangular matrix.

int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{1, 2};
jagged[2] = new int[]{1, 2, 3};
  • Array size is fixed once created and cannot be resized
  • All elements in a Java array must be of the same declared type
  • The length property (not a method) gives the number of elements in an array
If you need a resizable, dynamic list instead of a fixed-size array, Java's Collection Framework classes like ArrayList are the better choice.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course