Multidimensional arrays
What you will learn
A two-dimensional array in Java is an array whose components are references to other arrays. Rows may have different lengths, making jagged data possible.
public class Main { public static void main(String[] args) { int[][] seats = new int[2][3]; seats[1][2] = 1; System.out.println(seats.length); System.out.println(seats[1].length); System.out.println(seats[1][2]); }}Expected output:
231Both indices start at zero.
How it works
int[][] seats = new int[2][3] creates two rows of three integers. seats[r][c] first selects a row and then an element. seats.length counts rows and seats[r].length counts that row’s components. new int[2][] instead creates two null row references. Allocate each row before access. Nested loops must use the current row length. Arrays.deepToString renders nested array contents. Cloning the outer array alone does not clone any row. For non-null primitive rows, clone each row to copy every cell independently.
public class Main { public static void main(String[] args) { int[][] orders = {{2, 3}, {}, {7}}; int total = 0; for (int[] row : orders) { for (int value : row) total += value; } System.out.println(total); }}Expected output:
12The empty row contributes nothing. Each row has its own length.
Check a boundary or unusual input
import java.util.Arrays;public class Main { public static void main(String[] args) { int[][] source = {{2}, {5, 6}}; int[][] shallow = source.clone(); int[][] independent = new int[source.length][]; for (int i = 0; i < source.length; i++) independent[i] = source[i].clone(); shallow[0][0] = 9; System.out.println(Arrays.deepToString(source)); System.out.println(Arrays.deepToString(independent)); }}Expected output:
[[9], [5, 6]][[2], [5, 6]]Shallow copies share rows, unlike the independent copy.
Common mistakes
Do not use the first row length for every row or assume the outer array has any rows. If null rows are permitted, define a policy to skip or reject them. Array-of-arrays is not guaranteed to be a contiguous rectangular block.
Try it yourself
Write static int countCells(int[][] rows) to count all cells in a non-null jagged array with non-null rows and at most 100 total cells. Do not mutate rows.
Save each example independently as Main.java; compile with javac --release 21 -encoding UTF-8 Main.java and launch using java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Multidimensional arrays — knowledge check
Practice core behavior and boundary cases.
What does grid.length count?
Rows of new int[2][] initially?
Column bound for row r?
What happens if a shallow clone changes a shared row?
How many cells in {{1}, {}, {2,3}}?