Arrays.fill() in Java with Examples (original) (raw)

Last Updated : 25 Nov, 2024

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:

Java `

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));
}

}

`

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:

**Return Type: It does not return any value, but modifies the array directly.

**Exceptions:

**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 `

// 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 `

// 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));
}

}

`

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 `

// 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]]]