This post will discuss how to initialize all array elements with a specified value in Java.

We know that an array is initialized with a default value on creation. The default value is 0 for integral types. If we need to initialize an array with a different value, we can use any of the following methods:

1. Using Arrays.fill() method

The most common approach is to use the Arrays.fill() method, which internally uses a for-loop.

Download  Run Code

2. Using Collections.nCopies() method

Here, the idea is to call the Collections.nCopies() method to get a list and then convert it to an array using the List.toArray() method.

Download  Run Code

3. Using Arrays.setAll() method

Another alternative is to use the setAll() method of the Arrays class. It sets all elements of the specified array with the help of a generator method that accepts an index and generates a corresponding value for that index. We can easily set a specific value for each array element by returning the same value for every index.

Download  Run Code

4. Using Java 8

In Java 8 and above, we can use Stream, which offers many alternatives, as shown below:

Download  Run Code

Download  Run Code

Download  Run Code

Download  Run Code

That’s all about initializing all array elements with a specified value in Java.