Java Utility Library

Java Arrays - fill() Method



The java.util.Arrays.fill() method is used to assign the specified Object reference to each element of the specified range of the specified array of Objects.

Syntax

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

Parameters

a Specify the array to be filled.
fromIndex Specify the index of the first element (inclusive) to be filled with the specified value.
toIndex Specify the index of the last element (exclusive) to be filled with the specified value.
val Specify the value to be stored in all elements of the array.

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if fromIndex > toIndex.
  • Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length.
  • Throws ArrayStoreException, if the specified value is not of a runtime type that can be stored in the specified array.

Example:

In the example below, the java.util.Arrays.fill() method is used to fill the specified range in the specified array of objects with specified object reference.

import java.util.*;

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

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

    //fill the specified range of the array 
    //object with 5 Object value
    Arrays.fill(MyArr, 1, 4, 5);

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

The output of the above code will be:

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

❮ Java.util - Arrays