How to fill array values in Java?

Java 8Object Oriented ProgrammingProgramming

Let us first create an int array −

int[] arr = new int[10];

Now, fill array values. Here, the numbers get added from the index 2 to 7 −

Arrays.fill(arr, 2, 7, 100);

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      int[] arr = new int[10];
      System.out.println("Array = "+Arrays.toString(arr));
      Arrays.fill(arr, 2, 7, 100);
      System.out.println("Fill = "+Arrays.toString(arr));
   }
}

Output

Array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Fill = [0, 0, 100, 100, 100, 100, 100, 0, 0, 0]
raja
Published on 25-Apr-2019 13:29:38
Advertisements