Two-dimensional arrays help you store data in a table-like form with rows and columns. This is useful when you want to organize information in grids, like a chessboard or a calendar.
Two-dimensional arrays in Java
public class TwoDimensionalArrayExample { public static void main(String[] args) { // Declare and create a 2D array with 3 rows and 4 columns int[][] matrix = new int[3][4]; // Assign a value to a specific cell matrix[0][0] = 5; // Access a value from the array int value = matrix[0][0]; } }
The first bracket [] represents rows, and the second [] represents columns.
Array indices start at 0, so the first row is index 0 and the first column is index 0.
int[][] emptyArray = new int[0][0];
int[][] singleElementArray = {{42}};
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[2]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[3];
int[][] predefinedArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
This program creates a 2D array with 2 rows and 3 columns. It first prints the array with default values (which are zeros). Then it fills the array with multiplication results of (row + 1) and (col + 1) and prints the updated array.
public class TwoDimensionalArrayDemo { public static void main(String[] args) { // Create a 2D array with 2 rows and 3 columns int[][] table = new int[2][3]; // Print the array before assigning values System.out.println("Before assigning values:"); print2DArray(table); // Assign values to each cell for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[row].length; col++) { table[row][col] = (row + 1) * (col + 1); } } // Print the array after assigning values System.out.println("After assigning values:"); print2DArray(table); } // Helper method to print a 2D array public static void print2DArray(int[][] array) { for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { System.out.print(array[row][col] + " "); } System.out.println(); } } }
Accessing or assigning an element uses array[row][column] syntax.
Time complexity to access or assign one element is O(1).
Be careful not to access indexes outside the array size to avoid errors.
Two-dimensional arrays store data in rows and columns like a table.
Use array[row][column] to access or change values.
They are useful for grids, matrices, and tabular data.
