Home > Java > javaTutorial > How Do I Properly Initialize a Two-Dimensional Array in Java?

How Do I Properly Initialize a Two-Dimensional Array in Java?

DDD
Release: 2024-12-21 17:44:10
Original
211 people have browsed it

How Do I Properly Initialize a Two-Dimensional Array in Java?

Multidimensional arrays allow the organization of data into multiple dimensions, a common example being a two-dimensional array often used to represent tables or matrices. Java provides syntax for the seamless creation of two-dimensional arrays, which this article delves into.

Consider the code snippet:

int[][] multD = new int[5][];
multD[0] = new int[10];
Copy after login

The intent may be to establish a two-dimensional array containing 5 rows and 10 columns, however, this approach encounters syntactic irregularities. To correctly instantiate a two-dimensional array with these dimensions, the following syntax should be employed:

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

The provided construct serves as a concise representation that equates to the explicit definition:

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

It is imperative to remember that each element within the array is initialized to the default integer value, which is 0. This implies that the above definitions are equivalent to:

int[][] multi = new int[][] {
  { 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 can be further abbreviated to:

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

The above is the detailed content of How Do I Properly Initialize 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