Home >Java >javaTutorial >How Are Multidimensional Arrays Initialized and Accessed in Java?

How Are Multidimensional Arrays Initialized and Accessed in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 10:06:17179browse

How Are Multidimensional Arrays Initialized and Accessed in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn