This post will discuss how to declare and initialize two-dimensional arrays in Java.
There are several ways to declare and initialize two-dimensional arrays in Java, which are arrays of arrays that can store data in a tabular form. Here are some possible methods:
We can use the curly braces <> to declare and initialize a two-dimensional array with the values we want. We can use nested braces to specify the rows and columns of the array. For example:
import java . util . Arrays ; public class Main < public static void main ( String [ ] args ) < // declare and initialize a 2D array of integers int [ ] [ ] arr = // [[1, 2, 3], [4, 3, 6], [7, 8, 9]] System . out . println ( Arrays . deepToString ( arr ) ) ;
We can also initialize columns of different length with an array initializer. This will result in jagged array, which is an array whose elements are arrays of different dimensions and sizes. For example, the following code declare and initialize a 2D array with different sizes for each row.
We can also use the new operator to declare and initialize a two-dimensional array with a specified size. We can assign the dimension of the array using the index notation [row][column] . We can either seperate the declaration and initialization of two-dimensional arrays or combine them in a single line. For example:
import java . util . Arrays ; public class Main < public static void main ( String [ ] args ) < int [ ] [ ] arr1 ; // declare array arr1 = new int [ 3 ] [ 4 ] ; // allocate memory // [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] System . out . println ( Arrays . deepToString ( arr1 ) ) ; // combine both in a single line int [ ] [ ] arr2 = new int [ 3 ] [ 4 ] ; // [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] System . out . println ( Arrays . deepToString ( arr2 ) ) ;
Since we have not provided any initializer, the default value of 0 is assigned to each element in the case of int or long or short or byte array. The default value is null for strings, and 0.0 for double or float . Note that the second dimension in a two-dimensional array is optional. We can declare a two-dimensional array by only specifying the first dimension. However, we must specify the first dimension, otherwise the compiler will throw a compilation error.