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

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

DDD
DDDOriginal
2025-01-05 08:19:40747browse

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];

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];

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 }
};

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!

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