Java Utility Library

Java Arrays - fill() Method



The java.util.Arrays.fill() method is used to assign the specified int value to each element of the specified array of ints.

Syntax

public static void fill(int[] a, int val)

Parameters

a Specify the array to be filled.
val Specify the value to be stored in all elements of the array.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.Arrays.fill() method is used to fill the int array with specified int value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an int array
    int MyArr[] = {10, 2, -3, 35, 56};

    //printing array
    System.out.print("MyArr contains:"); 
    for(int i: MyArr)
      System.out.print(" " + i);

    //fill the array with 5 int value
    Arrays.fill(MyArr, 5);

    //printing array
    System.out.print("\nMyArr contains:"); 
    for(int i: MyArr)
      System.out.print(" " + i);   
  }
}

The output of the above code will be:

MyArr contains: 10 2 -3 35 56
MyArr contains: 5 5 5 5 5

❮ Java.util - Arrays