Multidimensional Array Initialization in Java
In Java, declaring and assigning values to multidimensional arrays can seem straightforward initially. However, it's essential to understand that Java doesn't have true multidimensional arrays. Instead, they are arrays of arrays.
Declaration:
int[][] myArray = new int[x][y]; // Declares a 2D array
or, with initialization:
int[][] myArray = { { 1, 2 }, { 3, 4 } };
Access:
int value = myArray[0][1]; // Accesses the element at row 0, column 1
Assignment:
myArray[1][0] = 5; // Assigns the value 5 to the element at row 1, column 0
Note: In your example, there is an error in the assignment of values. The correct syntax should be:
myStringArray[0][0] = "a string"; myStringArray[0][1] = "another string";
Remember, each element in a multidimensional array is itself an array. Therefore, to access or assign values, you must use multiple indices, corresponding to the dimensions.
The above is the detailed content of How Are Multidimensional Arrays Initialized and Accessed in Java?. For more information, please follow other related articles on the PHP Chinese website!