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

How Are Multidimensional Arrays Initialized and Accessed in Java?

Linda Hamilton
Release: 2024-11-30 10:06:17
Original
171 people have browsed it

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
Copy after login

or, with initialization:

int[][] myArray = { { 1, 2 }, { 3, 4 } };
Copy after login

Access:

int value = myArray[0][1]; // Accesses the element at row 0, column 1
Copy after login

Assignment:

myArray[1][0] = 5; // Assigns the value 5 to the element at row 1, column 0
Copy after login

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";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template