Java Single and Multidimensional Arrays

Java arrays have a fixed length and hold elements of one declared type.

Lesson 32 of 127Intermediate14 min read

Java arrays have a fixed length and hold elements of one declared type. A multidimensional array is an array whose elements are themselves arrays. This lesson shows how to traverse ordinary arrays, work with unequal row lengths and distinguish array copies from shared references.

Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.

Fixed size and indices

An array holds a fixed number of values of one component type. Its length is a field, and valid indices run from zero to length minus one.

Array indices begin at zero and end at length minus one. The length property belongs to the array object and is not a method call. An int array initializes its elements to zero; a reference array initializes them to null. Creating an array establishes storage for those elements, not fully constructed objects for every reference slot. Assign a real object before calling methods through such a slot.

Arrays of arrays

A multidimensional Java array is an array whose elements are arrays. Rows can be different lengths, and a row reference can even be null.

An int[][] does not require every row to have the same length. Each outer element references a separate int[] or can be null. A grid with equal row lengths is a useful convention, not a language guarantee. Traversing with rows[r].length respects the actual row shape. Using rows[0].length for every row can skip data or run beyond a shorter row.

Default values and element traversal

New primitive arrays receive default values such as zero or false. New reference arrays start with null elements until references are assigned.

An enhanced for loop reads each element in sequence and is convenient when indices are unnecessary. For primitive values, assigning to the loop variable does not update the array slot. Use an indexed loop for position-based updates. For object elements, the copied reference can still reach and mutate the object, even though reassigning the loop variable does not replace the original array element.

Mutation and shallow copies

Changing an array element mutates the array. Reassigning an array reference selects a different array, while clone makes only a shallow copy for nested arrays.

Cloning a multidimensional array copies only the outer array. Its row references still identify the same inner arrays. To separate every row, clone each non-null row as well. This remains shallow with respect to object elements inside a row. Choose the required copy depth deliberately instead of assuming that a new outer array makes all nested data independent.

Running the examples

Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.

How HarvestRows produces its output

The grid stores rows as separate arrays. The nested traversal reaches each row and then its actual elements, accumulating the supplied values. The outer length counts rows, while a row's length counts its own columns. Those are separate measurements, which is why a ragged structure can still be traversed correctly.

How RaggedRows produces its output

The outer array contains three row references. Iteration visits each actual row and reads its length, producing two, one and three. No rectangular allocation is required. A nested element loop could use the same row values to visit all six numbers without inventing a single shared column count.

How SharedArrayRows produces its output

clone creates a distinct outer array, so the identity comparison is false. Its first element still points to the same inner row as original[0]. Updating that row through copy therefore changes the value read through original. Clone the row separately if the two grids must support independent element updates.

Guard against missing rows

An array created with new int[3][] has three reference slots, initially null, rather than three constructed numeric rows. Assign each row before reading its length, or explicitly allow null rows and handle them during traversal. In contrast, new int[3][2] allocates three two-element rows with zero-filled primitive slots. These two allocation expressions describe different initial structures. For practice, construct a ragged grid containing one empty row and one populated row. A correct nested loop should visit the empty row without reading an invalid first element and still sum the populated row. Decide separately whether null rows are valid input or an error.

Java Summary

  • An array holds a fixed number of values of one component type. Its length is a field, and valid indices run from zero to length minus one.
  • A multidimensional Java array is an array whose elements are arrays. Rows can be different lengths, and a row reference can even be null.
  • New primitive arrays receive default values such as zero or false. New reference arrays start with null elements until references are assigned.
  • Changing an array element mutates the array. Reassigning an array reference selects a different array, while clone makes only a shallow copy for nested arrays.
  • Continue with Java exercises, Java quizzes and the Java study roadmap.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Java Single and Multidimensional Arrays in a complete program

Java
public class HarvestRows  {
    public static void main(String[] args)  {
        int[][] harvest =  {
            {
                6, 9
            },  {
                4, 7, 2
            }
        };
        int total = 0;
        for (int[] row : harvest) for (int value : row) total += value;
        System.out.println("Baskets: " + total);
    }
}
Output
Baskets: 28
Line-by-line explanation
  1. Line 12Evaluates "Baskets: " + total and prints Baskets: 28.
Example 2

Rows can have unequal lengths

Java
public class RaggedRows  {
    public static void main(String[] args)  {
        int[][] rows =  {
            {
                2, 4
            },  {
                7
            },  {
                1, 3, 5
            }
        };
        for (int[] row : rows) System.out.println(row.length);
    }
}
Output
2
1
3
Line-by-line explanation
  1. Line 12Evaluates row.length and prints the sequence 2 / 1 / 3 as the loop advances.
Example 3

Cloning the outer array still shares rows

Java
public class SharedArrayRows  {
    public static void main(String[] args)  {
        int[][] original =  {
            {
                1, 2
            }
        };
        int[][] copy = original.clone();
        copy[0][0] = 9;
        System.out.println(original[0][0]);
        System.out.println(original == copy);
    }
}
Output
9
false
Line-by-line explanation
  1. Line 10Evaluates original[0][0] and prints 9.
  2. Line 11Evaluates original == copy and prints false.

Java FAQ

What happens at an invalid array index?

Java throws ArrayIndexOutOfBoundsException. For an array of length three, valid indices are zero, one and two. An empty array has length zero and no valid index, so check its length before reading its first element.

Can an array grow after construction?

Its length cannot change. Create a new larger array and copy elements when fixed-size storage is required, or choose ArrayList for a collection that changes size. An array reference variable can be reassigned to another array without resizing the original object.

How do I make a full copy of a 2D array?

Copy every row as well as the outer array. A loop such as copy[i] = grid[i].clone(); for each row gives an independent copy. grid.clone() or Arrays.copyOf(grid, grid.length) alone copies only the outer array, so both arrays still share the same rows.

Is a Java 2D array stored as one block of memory?

No. It is an array of references to separate row arrays, which may be stored in different places and may have different lengths. This is why ragged arrays are possible and why grid[1] can be replaced by an entirely different row.

How do I find the number of columns in a 2D array?

Ask the row: grid[r].length. Using grid[0].length for every row only works when the array is rectangular. For a ragged array, read each row's own length inside the loop.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which loop respects ragged row lengths?

Multiple choicemedium

What does cloning int[][] copy first?

Java Quiz

2 questions to check what you learned.

  1. For an array of length four, what is the last valid index?

    • 3
    • 4
    • 5
  2. What does assigning to an enhanced-for int variable change?

    • Only that local loop variable
    • The current array element automatically
    • The array length