How do you define a two-dimensional array in Java?

In Java, one common way to define a two-dimensional array is by using square brackets to specify the size of rows and columns. For example, the following code defines a 3×4 two-dimensional array:

int[][] array = new int[3][4];

This will create a one-dimensional array with 3 elements, each element being a one-dimensional array containing 4 elements. Specific elements can be accessed by specifying the index, for example array[0][0] represents the element in the first row and first column. The entire two-dimensional array can be traversed using loops.

Another way to define a 2D array is by providing initial values during initialization. For example, the following code defines a 2×3 2D array and assigns initial values to each element.

int[][] array = {{1, 2, 3}, {4, 5, 6}};

This will create a one-dimensional array with 2 elements, where each element is itself an array with 3 elements. Specific elements can be accessed using the same indexing syntax.

bannerAds