๐ What is a Multidimensional Array?
A multidimensional array in Java is an array that contains other arrays as its elements.
The most commonly used type is the 2D array, which stores data in rows and columns like a table or matrix.
๐ In Java, a 2D array is just an array of 1D arrays.
๐๏ธ Declaration & Initialization
int[][] arr;๐ This declares a reference to a 2D integer array.
๐งฑ Memory Allocation
arr = new int[2][3];โ
This creates a 2D array with 2 rows and 3 columns. All elements are initialized to 0 by default.
๐ฆ Declaration + Initialization (Inline)
int[][] arr = {
{1, 2, 3},
{4, 5, 6}
};This creates and fills a 2D array at once.
1 2 3
4 5 6๐ Accessing Elements
You can access values using row and column indices:
System.out.println(arr[1][2]);6๐ก Here, arr[1][2] means 2nd row, 3rd column (index starts at 0).
๐ Traversing a 2D Array
Use nested loops:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}1 2 3
4 5 6Prints all elements of a 2D array row by row.
๐ง arr[i][j] โ accesses each element
๐จ๏ธ System.out.print(arr[i][j] + " ") โ prints element with a space
โฉ๏ธ System.out.println() โ moves to next line after each row
๐ซ Common Mistakes
โ
arr[2][0]will throwArrayIndexOutOfBoundsExceptionif there are only 2 rows (0and1).โ Always check:
arr.lengthfor total rowsarr[i].lengthfor number of columns in a specific row
๐งฉ Jagged Arrays (Irregular 2D Arrays)
Java supports jagged arrays โ where each row can have a different number of columns.
Jagged arrays are useful when data doesnโt fit a perfect grid.
๐ค Filling and Printing a Jagged Array
int[][] jagged = new int[2][]; // Step 1: Declare jagged array
jagged[0] = new int[3]; // Row 0 โ 3 columns
jagged[1] = new int[1]; // Row 1 โ 1 column
// Step 2: Assign values
jagged[0][0] = 10;
jagged[0][1] = 20;
jagged[0][2] = 30;
jagged[1][0] = 40;
// Step 3: Print the jagged array
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}10 20 30
40๐ฏ Real-World Use Cases
๐ Mathematical matrices
๐ Tabular data (like Excel sheets)
๐ฎ Game boards (Tic Tac Toe, Sudoku)
๐ผ๏ธ Image pixel storage