Declare and Initialize Two Dimensional Arrays in Java

In this post, we will see how to declare and initialize two dimensional arrays in Java.


 

1. Shortcut Syntax

The most common way to declare and initialize two dimensional arrays in Java is using shortcut syntax with array initializer:

 

2. New Operator

We can also declare and initialize two dimensional arrays by using new operator as shown below.

Since we have not provided any initializer, the default value of 0 is assigned to each element in case of int or long or short or byte array. For Strings, the default value is null and for double or float, the default value is 0.0.

 

3. Combining declaration and initialization

We can combine declaration and initialization of two dimensional arrays in a single line:

 

4. Skipping second dimension

The second dimension in a two dimensional array is optional and we can declare a two dimensional array by only specifying the first dimension, as shown below:

Please note that we must specify the first dimension, else compiler will throw a compilation error.

 

5. Jagged Array

A jagged array, also known as “array of arrays”, is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.

We know that a two dimensional array is nothing but an array of one dimensional arrays. Therefore, it is possible to create a two dimensional array in Java where individual one dimensional arrays has different length. To illustrate, consider below example

This will create a two dimensional array as shown below:

[0]
[0, 0]
[0, 0, 0]

 

6. Initialize columns with Array Initializer

We can also initialize columns of different length with an array initializer as shown below:

or

 
Above codes will result in:

[1]
[1, 2]
[1, 2, 3]

 

7. Reflection

We can also use reflection to create two dimensional arrays with the specified type and dimensions. For example, in order to create 3 x 4 two dimensional array, we can use

 

8. Initialize character array

To initialize a two dimensional array of characters, we can use String.toCharArray() function as shown below:

This is equivalent to:

 

9. Initialize Object array

We can initialize a two dimensional array of objects using new Type(), as shown below

or, we can initialize it with nulls using below syntax:

 
 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz