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:

1. Using array initializer

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:

Download  Run Code

 
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.

Download  Run Code

2. Using new operator

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:

Download  Run Code

 
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.

Download  Run Code

3. Initializing a 2D object array

We can also use the new operator to initialize a two-dimensional array of objects using new Type() syntax or initialize it with nulls using the index notation new Type[row][column]. For example:

Download  Run Code

4. Initializing a 2D character array

To initialize a two-dimensional array of characters, we can use the String.toCharArray() method in Java. This method converts the given string into a sequence of characters and returns a newly created character array. The length of the returned array is equal to the length of the string. To illustrate, consider the following example.

Download  Run Code

That’s all about declaring and initializing two-dimensional arrays in Java.