Java Arrays Fill | Filling Some Data Into The Array

Java Arrays Fill

Now let’s move on to our next method, which helps us fill the array. We know that the array elements when created initially, hold the default value of that particular data type. For example, if we have created an integer array, so initially all the elements are initialized to 0 after creation. After that, we are changing the values of the array elements. We can fill our array with another value, using the fill method of the Arrays class.

As the name of the method says, it is going to fill the array, with some value. Let’s try to implement this program –

import java.util.Arrays;
public class ArrayBasic {
public static void main(String[] args) {
int[] x = new int[10];
Arrays.fill(x, 10);
System.out.println(Arrays.toString(x));
}
}

In the above program, we have simply created an array to store 10 integers, and then called the fill method, which takes as arguments, the array to fill, and the value to fill. We have given our created array with reference variable x, and the value to be filled, which is 10. So, now all the elements of this array are 10.

You can try executing the program and observe the output. We can do a lot more than this. Even we can specify the range within which we want to fill the array with the specified value. Let’s try doing a program to demonstrate the filling of the array with some particular value within a specified range.

import java.util.Arrays;
public class ArrayBasic {
public static void main(String[] args) {
int[] x = new int[10];
Arrays.fill(x, 3,8, 100);
System.out.println(Arrays.toString(x));
}
}

Here, the fill method takes 4 arguments, out of which the first one is the array that we are going to fill, the second one is the starting index, the third one is the ending index, and the last one is the value that you want to fill into those indexes. This is to be noted that the ending index is not included. This means that if I have given 3 as my starting index and 8 as my ending index, then the value is filled from index 3 to index 7. The ending index itself is not included.

So, if you execute the above program, we can the elements from index 3 to 7 be initialized to value 100.