int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}, {
7, 8, 9
}
};Multidimensional Arrays in Java: Matrices and Jagged Arrays
Direct Answer & Core Concept
Multidimensional arrays in Java are arrays that contain other arrays as their elements. They are commonly used to represent tables, matrices, grids, and other structured data. In Java, a multidimensional array is actually an array of arrays, which makes it possible to create both regular and irregular structures.
This topic covers 2D arrays, matrix operations, nested loops, row and column traversal, and jagged arrays. Understanding these concepts is important for Java programming, coding interviews, competitive programming, and real-world data processing.
Detailed Explanation & Mechanics
What Is a Multidimensional Array in Java?
A multidimensional array is an array with more than one dimension. The most common type is a two-dimensional array, which contains rows and columns similar to a table.
For example, a 3 × 3 matrix has three rows and three columns. You can access an element by specifying both its row index and column index.
The structure looks like this:
Column
0 1 2
┌─────────
Row 0 │ 1 2 3
Row 1 │ 4 5 6
Row 2 │ 7 8 9Why Use Multidimensional Arrays?
Multidimensional arrays are useful when data naturally has rows and columns. For example, a school may store marks for multiple students and subjects using a 2D array.
They are also useful for mathematical matrices, game boards, seating arrangements, spreadsheets, image pixels, and grid-based problems.
int[][] marks = {
{
80, 75, 90
}, {
70, 85, 88
}, {
95, 92, 89
}
};Here, each row can represent a student and each column can represent a subject.
Types of Multidimensional Arrays in Java
Java supports arrays with multiple dimensions, although 2D arrays are by far the most commonly used. A 2D array uses two indexes, while a 3D array uses three indexes.
Common examples include:
2D arrays
3D arrays
Higher-dimensional arrays
Jagged arrays
int[][] twoD;
int[][][] threeD;In practice, most Java applications and coding problems use 2D arrays because they are easier to understand and work with.
Two-Dimensional Arrays in Java
A two-dimensional array is an array containing multiple one-dimensional arrays. You can think of it as a table containing rows and columns.
The first index identifies the row, and the second index identifies the column. Java starts both indexes from 0.
int[][] numbers = new int[3][4];This creates:
3 rows × 4 columnsSo the array contains 12 integer positions.
Declaring a 2D Array
You can declare a two-dimensional array using two pairs of square brackets. At this point, the array variable exists, but memory for the actual array has not necessarily been allocated.
int[][] matrix;You can also write the declaration using brackets after the variable name:
int matrix[][];The first style, int[][] matrix, is generally preferred because it clearly shows that the variable is a 2D array.
Creating a 2D Array
Use the new keyword to allocate a 2D array with a specific number of rows and columns.
int[][] matrix = new int[3][4];This creates 3 rows and 4 columns.
Rows = 3Columns = 4Total elements = 3 × 4 = 12Every integer element initially contains 0.
Initializing a 2D Array
You can initialize a 2D array directly using curly braces. Each inner brace represents one row.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}, {
7, 8, 9
}
};This creates three rows, and every row contains three elements.
It is one of the easiest ways to create a matrix when the values are already known.
Accessing Elements of a 2D Array
To access an element, provide the row index followed by the column index. Both indexes start from 0.
int[][] matrix = {
{
10, 20, 30
}, {
40, 50, 60
}
};
System.out.println(matrix[0][1]);Output:
20matrix[0][1] means row 0, column 1.
Changing Elements in a 2D Array
You can change an element by assigning a new value to its row and column position.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
matrix[1][2] = 100;
System.out.println(matrix[1][2]);Output:
100Only the selected element is changed; the other elements remain unchanged.
Understanding Row and Column Indexes
Consider this matrix:
int[][] matrix = {
{
10, 20, 30
}, {
40, 50, 60
}, {
70, 80, 90
}
};The indexes are:
Column 0 1 2Row 0 10 20 30Row 1 40 50 60Row 2 70 80 90For example:
matrix[2][1]means row 2, column 1, so the result is 80.
Traversing a 2D Array
Traversal means visiting every element of the array. A nested for loop is commonly used because one loop handles the rows and another handles the columns.
The outer loop moves through rows, while the inner loop moves through elements inside each row.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}, {
7, 8, 9
}
};
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();
}Output:
1 2 34 5 67 8 9How Nested Loops Work
The outer loop controls the row number. For every row, the inner loop visits each element in that row.
For example:
i = 0 → process row 0i = 1 → process row 1i = 2 → process row 2Inside each row:
j = 0 → first elementj = 1 → second elementj = 2 → third elementThis pattern is extremely common in Java matrix problems.
Using length with 2D Arrays
For a 2D array, matrix.length gives the number of rows. The length of an individual row is obtained using matrix[i].length.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
System.out.println(matrix.length);
System.out.println(matrix[0].length);Output:
23This distinction becomes especially important when working with jagged arrays.
Printing a 2D Array
A 2D array cannot be displayed properly using a simple System.out.println(matrix) because that prints an array reference.
You can use nested loops to print every value.
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();
}For a simpler approach, Java provides Arrays.deepToString().
import java.util.Arrays;
System.out.println(Arrays.deepToString(matrix));Taking 2D Array Input from the User
You can use the Scanner class to read rows and columns from the user.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int rows = sc.nextInt();
System.out.print("Enter columns: ");
int columns = sc.nextInt();
int[][] matrix = new int[rows][columns];
for (int i = 0;
i < rows;
i++) {
for (int j = 0;
j < columns;
j++) {
matrix[i][j] = sc.nextInt();
}
}After reading the values, nested loops can be used to display or process the matrix.
Sum of All Elements in a Matrix
You can calculate the total of all matrix elements by visiting every position and adding its value.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
int sum = 0;
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
sum += matrix[i][j];
}
}System.out.println("Sum = " + sum);Output:
Sum = 21This technique is useful for calculating totals, scores, quantities, and other aggregated values.
Finding the Largest Element
A nested loop can also be used to find the largest value in a matrix.
int[][] matrix = {
{
10, 25, 8
}, {
40, 15, 30
}, {
12, 50, 20
}
};
int max = matrix[0][0];
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}System.out.println("Maximum = " + max);Output:
Maximum = 50The same approach can be modified to find the minimum value.
Finding the Minimum Element
Start with the first element as the smallest value. Then compare every other element with the current minimum.
int min = matrix[0][0];
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
}
}
}System.out.println("Minimum = " + min);This approach works for both positive and negative numbers.
Row-Wise Traversal
Sometimes you need to process each row independently. The outer loop selects a row, and the inner loop processes every element in that row.
for (int i = 0;
i < matrix.length;
i++) {
int sum = 0;
for (int j = 0;
j < matrix[i].length;
j++) {
sum += matrix[i][j];
} System.out.println("Row " + i + " sum = " + sum);
}This technique is useful for calculating student marks, sales totals, scores, or other row-based data.
Column-Wise Traversal
For a rectangular matrix, you can also process one column at a time.
for (int j = 0;
j < matrix[0].length;
j++) {
int sum = 0;
for (int i = 0;
i < matrix.length;
i++) {
sum += matrix[i][j];
} System.out.println("Column " + j + " sum = " + sum);
}Here, the outer loop controls columns and the inner loop controls rows.
For jagged arrays, column-wise processing needs additional care because different rows can have different lengths.
Using Enhanced for Loop with 2D Arrays
You can use the enhanced for loop to make traversal simpler. The outer loop receives each row, while the inner loop receives each value from that row.
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
} System.out.println();
}This is useful when you only need to read values.
If you need row and column indexes, traditional nested for loops are usually more convenient.
Matrix Addition in Java
Two matrices can be added when they have the same number of rows and columns. Each result element is created by adding the corresponding elements from the two matrices.
int[][] a = {
{
1, 2
}, {
3, 4
}
};
int[][] b = {
{
5, 6
}, {
7, 8
}
};
int[][] result = new int[2][2];
for (int i = 0;
i < 2;
i++) {
for (int j = 0;
j < 2;
j++) {
result[i][j] = a[i][j] + b[i][j];
}
}The result is:
6 810 12Matrix Transpose
The transpose of a matrix changes rows into columns and columns into rows.
For example:
Original:1 2 34 5 6Transpose:1 42 53 6For a rectangular matrix, create a result array with reversed dimensions.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transpose = new int[columns][rows];
for (int i = 0;
i < rows;
i++) {
for (int j = 0;
j < columns;
j++) {
transpose[j][i] = matrix[i][j];
}
}What Is a Jagged Array?
A jagged array is a 2D array in which different rows can contain different numbers of elements.
Unlike a traditional rectangular matrix, every row does not need to have the same length.
int[][] numbers = {
{
1, 2
}, {
3, 4, 5
}, {
6
}
};The row lengths are:
Row 0 → 2 elementsRow 1 → 3 elementsRow 2 → 1 elementCreating a Jagged Array
You can create a jagged array by first specifying the number of rows and then creating each row separately.
int[][] numbers = new int[3][];
numbers[0] = new int[2];
numbers[1] = new int[3];
numbers[2] = new int[1];The rows now have different sizes.
This flexibility is one of the important features of Java's array-of-arrays design.
Initializing a Jagged Array Directly
You can also create a jagged array using nested initializer blocks.
int[][] numbers = {
{
10, 20
}, {
30, 40, 50
}, {
60
}
};Java automatically creates separate arrays for each row.
This is usually the simplest syntax when the data is already known.
Traversing a Jagged Array
When traversing a jagged array, always use matrix[i].length instead of assuming that every row has the same number of columns.
int[][] numbers = {
{
1, 2
}, {
3, 4, 5
}, {
6, 7, 8, 9
}
};
for (int i = 0;
i < numbers.length;
i++) {
for (int j = 0;
j < numbers[i].length;
j++) {
System.out.print(numbers[i][j] + " ");
} System.out.println();
}Output:
1 23 4 56 7 8 9Rectangular Array vs Jagged Array
A rectangular array has the same number of elements in every row. A jagged array allows each row to have its own length.
| Feature | Rectangular Array | Jagged Array |
|---|---|---|
| Row sizes | Same | Can differ |
| Structure | Table-like | Irregular |
| Memory | Regular structure | Flexible |
| Common use | Matrix | Variable-length data |
| Example | 3 × 3 | 2, 3, 1 elements |
Both are useful, and the correct choice depends on the structure of the data.
Three-Dimensional Arrays
Java can also create arrays with three dimensions. A 3D array can be thought of as a collection of 2D arrays.
int[][][] data = new int[2][3][4];This creates:
2 blocks3 rows per block4 columns per rowYou can access an element using three indexes:
data[0][1][2] = 100;Three-dimensional arrays are useful for some scientific, simulation, gaming, and data-processing problems.
Traversing a 3D Array
A 3D array requires three nested loops for complete traversal.
for (int i = 0;
i < data.length;
i++) {
for (int j = 0;
j < data[i].length;
j++) {
for (int k = 0;
k < data[i][j].length;
k++) {
System.out.print(data[i][j][k] + " ");
} System.out.println();
} System.out.println();
}Each loop represents a different dimension.
The same idea can be extended to arrays with more dimensions, although deeply nested arrays can become difficult to manage.
Multidimensional Arrays Are Arrays of Arrays
An important Java concept is that a multidimensional array is not exactly the same as a traditional fixed rectangular block of memory.
For example:
int[][] matrix = new int[3][4];The variable matrix refers to an array whose elements are references to row arrays.
Conceptually:
matrix
|
├── row 0 → [0, 0, 0, 0]
├── row 1 → [0, 0, 0, 0]
└── row 2 → [0, 0, 0, 0]This design allows Java to support jagged arrays naturally.
Checking the Number of Rows
The length property of the outer array tells you how many rows exist.
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
System.out.println(matrix.length);Output:
2Remember that length is a property, not a method.
Correct:
matrix.lengthNot:
matrix.length()Checking the Number of Columns
For a rectangular array, you can use the first row's length to find the number of columns.
System.out.println(matrix[0].length);However, this assumption is not safe for a jagged array.
For a jagged array, use:
matrix[i].lengthbecause each row may have a different number of elements.
Avoiding Array Index Errors
A common mistake is using an index outside the valid range.
For example:
int[][] matrix = new int[2][3];
System.out.println(matrix[2][0]);This causes:
ArrayIndexOutOfBoundsExceptionValid row indexes are 0 and 1, while valid column indexes are 0, 1, and 2.
Always make sure your indexes stay within the array's boundaries.
Null Rows in a Multidimensional Array
Because a multidimensional array contains references to row arrays, a row can be null.
int[][] matrix = new int[3][];
matrix[0] = new int[] {
1, 2
};
matrix[1] = null;
matrix[2] = new int[] {
3, 4
};Trying to access:
matrix[1].lengthwill cause a NullPointerException.
Therefore, when working with dynamically created jagged arrays, check whether a row is null when necessary.
Sorting Rows of a 2D Array
You can sort each individual row using Arrays.sort().
import java.util.Arrays;
int[][] matrix = {
{
5, 2, 8
}, {
9, 1, 4
}
};
for (int[] row : matrix) {
Arrays.sort(row);
}The result becomes:
2 5 81 4 9This sorts each row independently rather than sorting the complete matrix as one structure.
Using Arrays.deepToString()
The Arrays.deepToString() method is useful for displaying multidimensional arrays.
import java.util.Arrays;
int[][] matrix = {
{
1, 2, 3
}, {
4, 5, 6
}
};
System.out.println(Arrays.deepToString(matrix));Output:
[[1, 2, 3],[4, 5, 6]]For one-dimensional arrays, Arrays.toString() is commonly used, while Arrays.deepToString() is useful for nested arrays.
Passing a 2D Array to a Method
A 2D array can be passed to a method just like a normal array.
static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
} System.out.println();
}
}Call the method like this:
printMatrix(matrix);This is useful for keeping matrix-processing logic separate from the main() method.
Returning a 2D Array from a Method
A method can also return a 2D array.
static int[][] createMatrix() {
return new int[][] {
{
1, 2
}, {
3, 4
}
};
}You can store the returned array:
int[][] matrix = createMatrix();This approach is useful when a method needs to generate a matrix as its result.
Matrix Multiplication
Matrix multiplication is possible when the number of columns in the first matrix equals the number of rows in the second matrix.
For example:
A = 2 × 3B = 3 × 2The result will be:
2 × 2A basic implementation uses three nested loops.
int[][] a = {
{
1, 2, 3
}, {
4, 5, 6
}
};
int[][] b = {
{
7, 8
}, {
9, 10
}, {
11, 12
}
};
int[][] result = new int[2][2];
for (int i = 0;
i < 2;
i++) {
for (int j = 0;
j < 2;
j++) {
for (int k = 0;
k < 3;
k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}Matrix multiplication is a common Java programming and interview problem.
Diagonal Elements of a Matrix
For a square matrix, the main diagonal contains elements where the row index and column index are the same.
1 2 34 5 67 8 9The main diagonal is:
1 5 9You can access these elements using:
for (int i = 0;
i < matrix.length;
i++) {
System.out.println(matrix[i][i]);
}This technique is commonly used in matrix-related coding problems.
Complete Java Example: Matrix Operations
The following example demonstrates declaration, traversal, sum, and maximum-value calculation in one program.
public class MatrixExample {
public static void main(String[] args) {
int[][] matrix = {
{
10, 20, 30
}, {
40, 50, 60
}, {
70, 80, 90
}
};
int sum = 0;
int max = matrix[0][0];
System.out.println("Matrix:");
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
System.out.print(matrix[i][j] + " ");
sum += matrix[i][j];
if (matrix[i][j] > max) {
max = matrix[i][j];
}
} System.out.println();
} System.out.println("Sum = " + sum);
System.out.println("Maximum = " + max);
}
}Output:
Matrix:10 20 3040 50 6070 80 90Sum = 450Maximum = 90Complete Java Example: Jagged Array
Here is a simple example showing how different rows can contain different numbers of elements.
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] numbers = {
{
10, 20
}, {
30, 40, 50
}, {
60, 70, 80, 90
}
};
for (int i = 0;
i < numbers.length;
i++) {
System.out.print("Row " + i + ": ");
for (int j = 0;
j < numbers[i].length;
j++) {
System.out.print(numbers[i][j] + " ");
} System.out.println();
}
}
}Output:
Row 0: 10 20Row 1: 30 40 50Row 2: 60 70 80 90This example demonstrates why using numbers[i].length is important.
Common Mistakes with Multidimensional Arrays
1. Using the Wrong Index
matrix[3][2]may be invalid if the matrix does not have row index 3.
Always check the valid range before accessing an element.
2. Assuming Every Row Has the Same Length
This is especially dangerous with jagged arrays.
matrix[0].lengthdoes not necessarily equal:
matrix[1].length3. Forgetting Nested Loops
A 2D array normally requires two levels of iteration when you need to visit every element.
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
// process element
}
}4. Using length() Instead of length
Arrays use the length property.
Correct:
matrix.lengthIncorrect:
matrix.length()5. Accessing a Null Row
A row created as null cannot be accessed until an actual array is assigned to it.
if (matrix[i] != null) {
System.out.println(matrix[i].length);
}Best Practices for Multidimensional Arrays
Use meaningful variable names such as matrix, marks, grid, or table. When processing a matrix, use matrix.length for rows and matrix[i].length for the current row.
For jagged arrays, never assume that all rows have equal lengths. For larger or dynamically changing data structures, consider whether an ArrayList or another collection would be more suitable.
Multidimensional Array vs ArrayList
Arrays are useful when the size and structure are relatively stable. ArrayList is more flexible when you frequently need to add or remove elements.
For example:
int[][] matrix = new int[3][3];is suitable for a fixed matrix.
For dynamically growing data, collections such as:
ArrayList<ArrayList<Integer>>may provide more flexibility.
The choice depends on whether you need fixed-size indexed storage or dynamic collection behavior.
Time Complexity of Common Matrix Operations
For a matrix containing R rows and C columns, visiting every element takes approximately O(R × C) time.
For example, finding a sum or maximum requires checking every element once.
| Operation | Time Complexity |
|---|---|
| Access element | O(1) |
| Update element | O(1) |
| Traverse matrix | O(R × C) |
| Find maximum | O(R × C) |
| Find minimum | O(R × C) |
| Matrix addition | O(R × C) |
| Transpose | O(R × C) |
| Matrix multiplication | O(R × C × K) |
Understanding these complexities is useful for Java coding interviews and algorithm problems.
Frequently Asked Questions
What is a multidimensional array in Java?
A multidimensional array is an array containing other arrays. A 2D array is the most common example and can represent rows and columns.
What is a 2D array in Java?
A 2D array is an array of one-dimensional arrays. It is commonly used to represent matrices, tables, grids, and other row-column data.
What is a jagged array in Java?
A jagged array is a 2D array where different rows can have different numbers of elements.
How do you declare a 2D array in Java?
You can declare one using:
int[][] matrix;You can then allocate it with:
matrix = new int[3][4];How do you access a 2D array element?
Use two indexes:
matrix[row][column]For example:
matrix[1][2]accesses row 1, column 2.
What does matrix.length return?
For a 2D array, matrix.length returns the number of rows.
What does matrix[i].length return?
It returns the number of elements in row i. This is particularly important when working with jagged arrays.
Can Java arrays have different row sizes?
Yes. Java supports jagged arrays because a 2D array is an array of separate row arrays.
How do you print a 2D array?
You can use nested loops or:
Arrays.deepToString(matrix)Can a Java array have three dimensions?
Yes.
int[][][] data = new int[2][3][4];Java supports arrays with multiple dimensions.
Quick Revision
A multidimensional array contains arrays inside another array. The most common type is the 2D array, which represents rows and columns.
A matrix normally has a regular row-column structure, while a jagged array can contain rows with different lengths.
The most important syntax to remember is:
int[][] matrix = new int[3][4];Access an element with:
matrix[row][column]Traverse it with:
for (int i = 0;
i < matrix.length;
i++) {
for (int j = 0;
j < matrix[i].length;
j++) {
System.out.println(matrix[i][j]);
}
}Once you understand these patterns, you can solve many Java matrix and grid-based programming problems.
Graphic and Image Design Ideas
Graphic 1: 2D Array Structure
Create a clean visual showing:
Java 2D Array
Column
0 1 2
┌───────────
Row 0│ 10 20 30
Row 1│ 40 50 60
Row 2│ 70 80 90Label the row index, column index, and element value.
Graphic 2: Java Matrix Visualization
Show a 3 × 3 matrix with arrows pointing to:
matrix[0][0]matrix[1][2]matrix[2][1]This will help beginners understand how two indexes locate an element.
Graphic 3: Rectangular vs Jagged Array
Use a side-by-side comparison:
Rectangular Jagged1 2 3 1 24 5 6 3 4 57 8 9 6Clearly label the first as Same Row Length and the second as Different Row Length.
Graphic 4: Nested Loop Visualization
Show:
Outer Loop → Rows↓Inner Loop → Columns↓matrix[i][j]This is particularly useful for beginners learning matrix traversal.
Graphic 5: Matrix Transpose
Show:
Original Transpose1 2 3 1 44 5 6 → 2 5 3 6Use arrows to demonstrate how rows become columns.
Graphic 6: 3D Array Concept
Show three separate 2D grids stacked together:
Block 0[][][]Block 1[][][]Block 2[][][]Label the three dimensions as block → row → column.
Runnable Code Example: Multidimensional Arrays in Java
Java 17+import java.util.Arrays;
public class JaggedArrayDemo {
public static void main(String[] args) {
// Jagged array with different column counts per row
int[][] jagged = new int[3][];
jagged[0] = new int[] {
1, 2
};
jagged[1] = new int[] {
3, 4, 5, 6
};
jagged[2] = new int[] {
7, 8, 9
};
System.out.println("Jagged Array: " + Arrays.deepToString(jagged));
System.out.println("Row 1 Length: " + jagged[1].length);
// 4
}
}