What does the method fill(obj[], int fromIndex, int toIndex, int val) do in java?

Java 8Object Oriented ProgrammingProgramming

The fill(object[] a, int fromIndex, int toIndex, object val) method of the class java.util.Arrays assign the specified Object reference to each element of the specified range of the specified array of objects. The range to be filled extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be filled is empty)

Example

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      Object arr[] = new Object[] {1.2, 5.6, 3.4, 2.9, 9.7};
      System.out.println("Actual values: ");

      for (Object value : arr) {
         System.out.println("Value = " + value);
      }
      Arrays.fill(arr, 1, 3, 12.2);
      System.out.println("New values after using fill() method: ");

      for (Object value : arr) {
         System.out.println("Value = " + value);
      }
   }
}

Output

Actual values:
Value = 1.2
Value = 5.6
Value = 3.4
Value = 2.9
Value = 9.7
New values after using fill() method:
Value = 1.2
Value = 12.2
Value = 12.2
Value = 2.9
Value = 9.7

 

raja
Published on 08-Feb-2018 08:04:14
Advertisements