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


The fill(int[] a, int val) method of the java.util.Arrays class assigns the specified int value to each element of the specified array of integers.

Example

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      int arr[] = new int[] {1, 6, 3, 2, 9};
      System.out.println("Actual values: ");

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

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

Output

Actual values:
Value = 1
Value = 6
Value = 3
Value = 2
Value = 9
New values after using fill() method:
Value = 18
Value = 18
Value = 18
Value = 18
Value = 18

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Feb-2020

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements