Home > Java > javaTutorial > How Can I Create a Two-Dimensional Array in Java?

How Can I Create a Two-Dimensional Array in Java?

DDD
Release: 2025-01-05 08:19:40
Original
741 people have browsed it

How Can I Create a Two-Dimensional Array in Java?

Creating Two-Dimensional Arrays in Java

The question raised concerns the correct syntax for creating a two-dimensional array with specific dimensions. The provided code fragment initializes a multi-dimensional array but does not conform to the correct syntax for specifying dimensions.

To create a two-dimensional array of integers with 5 rows and 10 columns in Java, the appropriate syntax is:

int[][] multi = new int[5][10];
Copy after login

This syntax declares a two-dimensional array named multi with 5 elements, each of which is an array of 10 integers. To put it simply, multi is a 5x10 grid of integer values.

Another approach is to create the array explicitly, setting each row to have the desired length:

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];
Copy after login

This method creates a 5x10 grid and initializes each element to the default value for integers, which is 0.

An even more concise way to create and initialize a two-dimensional array is using curly braces:

int[][] multi = {
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
Copy after login

This method initializes the array to the values specified within the curly braces.

The above is the detailed content of How Can I Create a Two-Dimensional Array 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template