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


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

 

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Feb-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements