This post will discuss how to initialize a 2D array with a specific value in Java.

1. Static Initialization

To initialize a 2D array with default storage of their respective types, you can make use of the explicit initialization property of the arrays. i.e., if you don’t provide any initializer, the default value is assigned to each array element.

The default value is 0 for int, short, long, and byte array, 0.0 for double and float arrays, and null for String array. This is demonstrated below for a 4 × 5 integer matrix.

Download  Run Code

Output:

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

 
Following is an equivalent version of the above code using an array initializer:

Download  Run Code

Output:

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

2. Using Arrays.fill() method

The recommended approach to initialize an array with any value is using the Arrays.fill() method. For a 2D array, Arrays.fill() can be called for each array using a for-loop.

Download  Run Code

Output:

[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

 
In Java 8 or later, this can be done trivially using streams without any loops.

Download  Run Code

Output:

[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

3. Jagged Array

Note that it is feasible to create a 2D array whose individual arrays have different lengths. Such an array is called a jagged array. To illustrate, consider the following example, which declares and initializes a jagged array. It uses an array initializer to fill the array elements with values.

Download  Run Code

Output:

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

 
You can separate the declaration of the jagged array with its initialization:

Download  Run Code

Output:

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

That’s all about initializing a 2D array with a specific value in Java.