About Lesson
In Java, a multidimensional array is an array of arrays. It is a convenient way to represent data that has multiple dimensions or axes, such as a matrix or a table. Here are some examples:
- Declaring a two-dimensional array: To declare a two-dimensional array, you need to specify the type of the elements in the array and the size of each dimension:
int[][] matrix; // declare a two-dimensional array of integers
String[][] table; // declare a two-dimensional array of strings
- Initializing a two-dimensional array: To initialize a two-dimensional array, you need to create a new array object and assign it to the array variable. You can either specify the initial values of the array or leave the array uninitialized:
// initialize a two-dimensional array of integers with 3 rows and 4 columns
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// initialize a two-dimensional array of strings with 2 rows and 2 columns
String[][] table = new String[2][2];
table[0][0] = "Alice";
table[0][1] = "Bob";
table[1][0] = "Charlie";
table[1][1] = "David";
- Accessing elements of a two-dimensional array: You can access the elements of a two-dimensional array by specifying the indices of the row and column you want to access:
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int firstElement = matrix[0][0]; // access the first element (row 0, column 0)
int thirdRowFourthColumn = matrix[2][3]; // access the element in the third row and fourth column
- Changing elements of a two-dimensional array: You can change the value of an element in a two-dimensional array by assigning a new value to it:
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
matrix[0][0] = 10; // change the value of the first element to 10
matrix[1][2] = matrix[0][1] + matrix[2][3]; // assign the sum of the second element in the first row and the fourth element in the third row to the third element in the second row
You can create arrays with any number of dimensions in Java. To access elements of an n-dimensional array, you need to specify n indices. However, keep in mind that as the number of dimensions increases, the complexity of the array increases as well, and it may become harder to work with the array.