Java Two Dimensional Arrays
A two-dimensional array in Java is an array of arrays, where each element of the main array is an array of elements. This type of array is useful for storing and manipulating data in a tabular format, where each row represents a different record and each column represents a different field.
Here is an example of how you can declare and initialize a two-dimensional array in Java:
int[][] matrix = new int[3][4];
Output:
0 0 0 0
0 0 0 0
0 0 0 0
This code creates a two-dimensional array called matrix
with 3 rows and 4 columns. Each element of the array is initialized to 0.
You can also initialize a two-dimensional array with specific values using an array literal:
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Output:
1 2 3 4
5 6 7 8
9 10 11 12
This code creates a two-dimensional array called matrix
with 3 rows and 4 columns, and initializes the elements of the array with the given values.
To access an element of the two-dimensional array, you can use two sets of square brackets — one for the row index and one for the column index. For example, to access the element at row 1, column 2, (Remember Arrays have an index starting from 0) you can use the following code:
int element = matrix[1][2];
Output:
7
This code assigns the value 7 to the element
variable.
You can also use a loop to iterate over the elements of a two-dimensional array. For example, the following code prints all the elements of the matrix
array to the console:
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 3 4
5 6 7 8
9 10 11 12
This code uses a nested loop to iterate over the rows and columns of the matrix
array and prints the elements to the console.
Two-dimensional arrays are a useful data structure in Java and can be used to store and manipulate tabular data in your programs.
Find out more about Java here.