Two-Dimensional Arrays
A two-dimensional array (2D array) in Java is an array of arrays used to store data in a tabular (row–column) structure. It is commonly used for matrices, grids, tables, and multi-level data processing. This topic is important for logic building, real-time scenarios, and interviews.
What Is a Two-Dimensional Array?
- Stores data in rows and columns
- Each element is accessed using two indexes
- Internally implemented as array of arrays
- Supports jagged (irregular) structures
Declaration of 2D Array
Syntax
dataType[][] arrayName;
or
dataType arrayName[][];
Preferred:
int[][] matrix;
Creation of 2D Array
int[][] matrix = new int[3][4];
- 3 rows
- 4 columns per row
- Default values are assigned automatically
Default Values in 2D Arrays
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| boolean | false |
| char | '\u0000' |
| Object | null |
Initialization of 2D Array
1. Static Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
2. Dynamic Initialization
int[][] matrix = new int[2][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
Accessing 2D Array Elements
int value = matrix[1][2]; // 6
⚠️ Invalid index results in:
ArrayIndexOutOfBoundsException
Length Property in 2D Arrays
int rows = matrix.length;
int cols = matrix[0].length;
- matrix.length → number of rows
- matrix[row].length → number of columns in that row
Traversing a 2D Array
Using Nested for Loop
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();
}
Using Enhanced for-each Loop
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
Jagged Arrays (Irregular 2D Arrays)
In Java, rows can have different column sizes.
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[3];
jagged[2] = new int[1];
Example: Matrix Addition
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
Memory Representation (Conceptual)
- 2D arrays are arrays of references
- Each row is a separate array
- Allows jagged structures
Common Use Cases
- Matrix operations
- Tables and grids
- Game boards
- Multi-level datasets
Common Beginner Mistakes
- Assuming all rows have equal columns
- Incorrect loop bounds
- Confusing row and column indexes
- Hardcoding sizes
- Ignoring jagged array behavior
Interview-Ready Answers
Short Answer
A two-dimensional array stores data in a row–column format using an array of arrays.
Detailed Answer
In Java, a two-dimensional array is implemented as an array of arrays, allowing both rectangular and jagged structures. It is accessed using two indices and commonly used for matrices and tabular data.
Key Takeaway
Two-dimensional arrays provide a structured way to manage tabular data. Understanding their memory model and traversal is essential for efficient and correct Java programs.
2D Array Examples and Patterns
1. Declare and Initialize a 2D Array (Literal)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Explanation
- 2 rows and 3 columns.
- Each inner {} represents a row.
2. Create a 2D Array with Fixed Size
int[][] matrix = new int[2][3];
Explanation
- Creates 2 rows and 3 columns.
- Default value for int elements is 0.
3. Assign Values to a 2D Array
int[][] matrix = new int[2][2];
matrix[0][0] = 10;
matrix[0][1] = 20;
matrix[1][0] = 30;
matrix[1][1] = 40;
Explanation
- Accessed using matrix[row][column].
- Index starts from 0.
4. Access a Single Element
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(matrix[1][0]);
Explanation
- Accesses element in 2nd row, 1st column.
- Output: 3
5. Traverse 2D Array Using Nested for Loops
int[][] matrix = {{1, 2}, {3, 4}};
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();
}
Explanation
- Outer loop → rows.
- Inner loop → columns.
6. Traverse 2D Array Using Enhanced for-each
int[][] matrix = {{1, 2}, {3, 4}};
for (int[] row : matrix) {
for (int val : row) {
System.out.println(val);
}
}
Explanation
- Cleaner syntax.
- Best for read-only traversal.
7. Find Number of Rows and Columns
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
System.out.println(matrix.length); // rows
System.out.println(matrix[0].length); // columns
Explanation
- matrix.length → number of rows.
- matrix[row].length → columns in that row.
8. Sum of All Elements in 2D Array
int[][] matrix = {{1, 2}, {3, 4}};
int sum = 0;
for (int[] row : matrix) {
for (int val : row) {
sum += val;
}
}
System.out.println(sum);
Explanation
- Adds all elements.
- Output: 10
9. Row-Wise Sum
int[][] matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) {
int rowSum = 0;
for (int j = 0; j < matrix[i].length; j++) {
rowSum += matrix[i][j];
}
System.out.println("Row " + i + " sum = " + rowSum);
}
Explanation
- Calculates sum for each row separately.
10. Column-Wise Sum
int[][] matrix = {{1, 2}, {3, 4}};
for (int col = 0; col < matrix[0].length; col++) {
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][col];
}
System.out.println("Column " + col + " sum = " + colSum);
}
Explanation
- Fixes column index.
- Iterates rows.
11. Find Maximum Element in 2D Array
int[][] matrix = {{1, 9}, {3, 4}};
int max = matrix[0][0];
for (int[] row : matrix) {
for (int val : row) {
if (val > max) {
max = val;
}
}
}
System.out.println(max);
Explanation
- Tracks largest value.
- Output: 9
12. Find Minimum Element in 2D Array
int[][] matrix = {{1, 9}, {3, 4}};
int min = matrix[0][0];
for (int[] row : matrix) {
for (int val : row) {
if (val < min) {
min = val;
}
}
}
System.out.println(min);
Explanation
- Tracks smallest value.
- Output: 1
13. Matrix Addition
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
Explanation
- Adds corresponding elements.
- Common interview question.
14. Matrix Multiplication (Basic)
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{2, 0}, {1, 2}};
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 < 2; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
Explanation
- Uses three nested loops.
- Very common advanced interview example.
15. Transpose of a Matrix
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[][] transpose = new int[3][2];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
Explanation
- Rows become columns.
- Output matrix size changes.
16. Diagonal Elements of Square Matrix
int[][] matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) {
System.out.println(matrix[i][i]);
}
Explanation
- Diagonal condition: row == column.
- Output: 1 4
17. Check if Matrix Is Square
int[][] matrix = {{1, 2}, {3, 4}};
boolean isSquare = true;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i].length != matrix.length) {
isSquare = false;
break;
}
}
System.out.println(isSquare);
Explanation
- Rows = columns.
- Output: true
18. Jagged Array (Irregular 2D Array)
int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};
Explanation
- Each row can have different column sizes.
- Supported in Java.
19. Traverse Jagged Array
int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++) {
System.out.println(jagged[i][j]);
}
}
Explanation
- Inner loop uses jagged[i].length.
- Avoids out-of-bounds errors.
20. Interview Summary Example (2D Array Traversal)
int[][] matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
}
Explanation
- Demonstrates:
- Declaration
- Indexing
- Nested loops
- Extremely common interview question.