Arrays.fill() in Java with Examples
The Arrays.fill() is a method in the java.util.Arrays class. This method assigns a specified value to each element of an entire array or a specified range within the specified array.
Example:
Now let’s understand this with the below simple example to fill an entire array with a specified value:
import java.util.Arrays;
public class GFG {
public static void main(String[] args) {
// Create an array of 5 integers
int[] arr = new int[5];
// Fill the entire array with the value 2
Arrays.fill(arr, 2);
System.out.println("" + Arrays.toString(arr));
}
}
Output
[2, 2, 2, 2, 2]
Table of Content
Syntax of Arrays.fill() method
public static void fill(int[] a, int val)
public static void fill(int[] a, int fromIndex, int toIndex, int val)
Parameters:
a:
Array to be filled.val:
Value to assign to each element of the array.fromIndex:
Starting index (inclusive) for filling.toIndex:
Ending index (exclusive) for filling.
Return Type: It does not return any value, but modifies the array directly.
Exceptions:
- IllegalArgumentException: Thrown if from_Index > to_Index
ArrayIndexOutOfBoundsException:
Thrown iffromIndex
ortoIndex
is outside the valid range (i.e.,fromIndex < 0
ortoIndex > a.length
).
Examples of Arrays.fill() in Java
Java Program to Fill a Specific Range in an Array
In this example, we will be using Arrays.fill() method to update only a specific range of elements within the array and remaining other elements will not change.
// Java program to fill a subarray array with
// given value
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int arr[] = {2, 2, 2, 2, 2, 2, 2,};
// Fill from index 1 to index 4
Arrays.fill(arr, 1, 4, 5);
System.out.println(Arrays.toString(arr));
}
}
Output
[2, 5, 5, 5, 2, 2, 2]
Java Program to Fill a 2D Array with a Specific Value
In this example, we will use Arrays.fill()
method to fill all the elements of each row in a 2D array with a specific value i.e. 5. Here, we will be using a for-each loop to iterate over each row of the array.
// Java program to fill a 2D array with
// given value
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int [][]arr = new int[2][2];
// Fill each row with 5
for (int[] r : arr)
Arrays.fill(r, 5);
System.out.println(Arrays.deepToString(arr));
}
}
Output
[[5, 5], [5, 5]]
Java Program to Fill a 3D Array with a Specific Value
In this example, again we will use Arrays.fill() method to fill each element of a 3D array with a specific value i.e. 2. Here, we will be using Nested loops to fill each row and column in the 3D array.
// Java program to fill a 3D array with
// given value.
import java.util.Arrays;
class GFG {
public static void main(String[] args) {
int[][][] arr = new int[2][2][2];
// Fill each row with 2
for (int[][] r : arr) {
for (int[] c : r) {
Arrays.fill(c, 2);
}
}
System.out.println(Arrays.deepToString(arr));
}
}
Output
[[[2, 2], [2, 2]], [[2, 2], [2, 2]]]