Multidimensional Arrays in Java – 2D and 3D Arrays with Examples
A multidimensional array is an array whose elements are themselves arrays. The most common kind is the two-dimensional (2D) array, which models a table of rows and columns: a seating plan, a spreadsheet of marks, a game board or a mathematical matrix. Java also supports three or more dimensions.
This tutorial explains how to declare, create and loop over 2D and 3D arrays, how they are stored, and how to perform common tasks such as row and column totals and matrix operations.
1. What Is a Multidimensional Array?
In Java, a 2D array is really an array of arrays: the outer array holds references to the row arrays. You access an element with two indexes, grid[row][column], both starting at 0.
int[][] grid = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] seats = { // rows written as nested braces
{1, 0, 1, 1},
{0, 0, 1, 0},
{1, 1, 1, 1}
};
int rows = seats.length; // number of rows
int cols = seats[0].length; // number of columns in row 0
2. Creating, Accessing and Printing a 2D Array
import java.util.Arrays;
public class TwoDBasics {
public static void main(String[] args) {
// 3 rows, 4 columns
int[][] grid = new int[3][4];
grid[0][1] = 5; // row 0, column 1
grid[2][3] = 9; // row 2, column 3
// Initialise with values
int[][] seats = {
{1, 0, 1, 1},
{0, 0, 1, 0},
{1, 1, 1, 1}
};
System.out.println("rows = " + seats.length + ", columns = " + seats[0].length);
System.out.println("seats[1][2] = " + seats[1][2]);
// Nested loops: outer for rows, inner for columns
for (int r = 0; r < seats.length; r++) {
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 1 ? "X " : "_ ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(grid));
}
}
rows = 3, columns = 4 seats[1][2] = 1 X _ X X _ _ X _ X X X X [[0, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 9]]
- The outer loop walks the rows; the inner loop walks the columns of the current row.
- Use
seats[r].lengthin the inner loop so the code also works when rows have different lengths. Arrays.deepToString()prints nested arrays;Arrays.toString()would print only references.
3. Row and Column Calculations
Tables of data often need totals per row and statistics per column. Here each row is a student and each column a subject:
public class MarksTable {
public static void main(String[] args) {
String[] students = {"Asha", "Ravi", "Meera"};
String[] subjects = {"Maths", "Science", "English"};
int[][] marks = {
{88, 92, 79},
{65, 70, 81},
{94, 89, 90}
};
// Row totals: one per student
for (int s = 0; s < marks.length; s++) {
int total = 0;
for (int m : marks[s]) total += m;
System.out.printf("%-6s total %3d, average %.1f%n", students[s], total, total / 3.0);
}
// Column maximums: one per subject
for (int sub = 0; sub < subjects.length; sub++) {
int best = 0;
for (int[] row : marks) best = Math.max(best, row[sub]);
System.out.println("Top " + subjects[sub] + " mark: " + best);
}
}
}
Asha total 259, average 86.3 Ravi total 216, average 72.0 Meera total 273, average 91.0 Top Maths mark: 94 Top Science mark: 92 Top English mark: 90
Row work loops over marks[s]; column work fixes the column index and loops over the rows.
4. Matrix Operations
2D arrays are the natural representation of mathematical matrices. Addition works element by element, multiplication combines rows of the first matrix with columns of the second, and transpose swaps rows and columns:
import java.util.Arrays;
public class MatrixOps {
static int[][] add(int[][] a, int[][] b) {
int[][] r = new int[a.length][a[0].length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[0].length; j++)
r[i][j] = a[i][j] + b[i][j];
return r;
}
static int[][] multiply(int[][] a, int[][] b) { // (m x n) * (n x p) = (m x p)
int[][] r = new int[a.length][b[0].length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < b[0].length; j++)
for (int k = 0; k < b.length; k++)
r[i][j] += a[i][k] * b[k][j];
return r;
}
static int[][] transpose(int[][] a) {
int[][] r = new int[a[0].length][a.length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[0].length; j++)
r[j][i] = a[i][j];
return r;
}
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
System.out.println("a + b = " + Arrays.deepToString(add(a, b)));
System.out.println("a x b = " + Arrays.deepToString(multiply(a, b)));
System.out.println("transpose a = " + Arrays.deepToString(transpose(a)));
int[][] wide = {{1, 2, 3}, {4, 5, 6}};
System.out.println("transpose of 2x3 = " + Arrays.deepToString(transpose(wide)));
}
}
a + b = [[6, 8], [10, 12]] a x b = [[19, 22], [43, 50]] transpose a = [[1, 3], [2, 4]] transpose of 2x3 = [[1, 4], [2, 5], [3, 6]]
Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second, and its three nested loops make it O(n³) for square matrices.
5. Three-Dimensional Arrays
A 3D array adds another level, such as building → floor → room. Each extra dimension adds another index and another nested loop:
public class ThreeDArray {
public static void main(String[] args) {
// [building][floor][room]: number of people in each room
int[][][] people = new int[2][3][4];
people[0][1][2] = 6;
people[1][2][0] = 3;
people[1][0][3] = 5;
int total = 0;
for (int[][] building : people)
for (int[] floor : building)
for (int room : floor)
total += room;
System.out.println("dimensions: " + people.length + " x " + people[0].length + " x " + people[0][0].length);
System.out.println("people in building 1, floor 2, room 0: " + people[1][2][0]);
System.out.println("total people: " + total);
}
}
dimensions: 2 x 3 x 4 people in building 1, floor 2, room 0: 3 total people: 14
Arrays with more than three dimensions are legal but rarely useful; at that point a class or a map usually models the data more clearly.
6. How 2D Arrays Are Stored
Because a 2D array is an array of arrays, new int[3][4] creates four objects: one outer array of 3 references and three inner arrays of 4 ints each. Consequences:
- Rows can have different lengths; such arrays are called jagged arrays.
- You can create only the outer array first:
new int[3][], and add rows later. - A whole row can be swapped by reassigning one reference:
grid[0] = new int[] {...}. - Looping row by row (row-major order) is faster than column by column, because each row is stored contiguously.
7. Copying and Comparing 2D Arrays
grid.clone()copies only the outer array; the rows are shared. For a full copy, clone each row:Arrays.stream(grid).map(int[]::clone).toArray(int[][]::new).Arrays.equals()compares only row references; useArrays.deepEquals().Arrays.fill()works on one row at a time.
8. Summary
- A multidimensional array is an array of arrays, accessed with one index per dimension.
- 2D arrays model tables and matrices:
arr[row][col], witharr.lengthrows andarr[r].lengthcolumns. - Process them with nested loops, outer for rows and inner for columns.
- Rows are separate objects, so they can differ in length and must be deep-copied and deep-compared.
- Use
Arrays.deepToString()to print andArrays.deepEquals()to compare.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is a multidimensional array in Java?
An array whose elements are arrays. A 2D array represents rows and columns; a 3D array adds a third level. Each element is accessed with one index per dimension.
Q2. How do I declare a 2D array?
int[][] matrix = new int[rows][cols];, or initialise it directly with nested braces: int[][] m = {{1, 2}, {3, 4}};.
Q3. How do I get the number of rows and columns?
matrix.length gives the number of rows, and matrix[r].length gives the number of columns in row r.
Q4. How do I print a 2D array?
Use nested loops for custom formatting, or Arrays.deepToString(matrix) for a quick view.
Q5. Is a 2D array stored as one block of memory in Java?
No. It is an outer array of references to separate row arrays. Each row is contiguous, but rows may be anywhere on the heap.
Q6. Can rows of a 2D array have different lengths?
Yes. Such arrays are called jagged arrays. Create the outer array with new int[rows][] and assign each row separately.
Q7. Is it necessary to specify the column size?
No, only the first dimension is required: new int[3][] is valid. new int[][3] is not.
Q8. How do I loop over a 2D array with for-each?
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
Q9. How do I multiply two matrices in Java?
Use three nested loops: for each row i of the first and column j of the second, sum a[i][k] * b[k][j] over k, as in the multiply() method above.
Q10. How do I transpose a matrix?
Create a new array with swapped dimensions and copy each element: result[j][i] = matrix[i][j].
Q11. How do I copy a 2D array?
Copy each row. clone() on the outer array only copies the row references. A deep copy: Arrays.stream(m).map(int[]::clone).toArray(int[][]::new).
Q12. How do I compare two 2D arrays?
Use Arrays.deepEquals(a, b). Arrays.equals() would compare row references instead of values.
Q13. What are the default values in a 2D array?
The same as for 1D arrays: 0, false, '\u0000' or null. If only the outer array is created (new int[3][]), the rows themselves are null.
Q14. How many dimensions can a Java array have?
Up to 255 according to the JVM specification. In practice, more than three dimensions is rare.
Q15. How do I take input into a 2D array?
Read the number of rows and columns, create the array, then fill it with nested loops using Scanner.nextInt().
Q16. How do I find the sum of each row or column?
For rows, loop over each row's elements. For columns, fix the column index and loop over all rows, as shown in the marks table example.
Q17. Why is row-by-row iteration faster?
Each row is stored in one contiguous block, so reading along a row uses the CPU cache well. Jumping down a column touches a different row object each time.
Q18. What is a 3D array used for?
Data with three coordinates, such as building/floor/room, layers of an image, or a time series of grids.
Q19. What happens if I access a missing row?
An index outside the outer array throws ArrayIndexOutOfBoundsException; using a row that was never created (null) throws NullPointerException.
Q20. Should I use a 2D array or a List of Lists?
Use a 2D array for fixed-size grids and numeric matrices. Use List<List<T>> when rows are added or removed or grow over time.