Initialize an Array with Reflection Utilities in Java

Java 8Object Oriented ProgrammingProgramming

An array can be initialized using the method java.util.Arrays.fill() that is a utility method provided in the java.util.Arrays class. This method assigns the required value to all the elements in the array or to all the elements in the specified range.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] arg) {
      int[] arr = {2, 5, 8, 1, 9};
      System.out.print("The array elements are: ");
      for (int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      Arrays.fill(arr, 9);
      System.out.print("\nThe array elements after Arrays.fill() method are: ");
      for (int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
   }
}

Output

The array elements are: 2 5 8 1 9
The array elements after Arrays.fill() method are: 9 9 9 9 9

Now let us understand the above program.

First, the elements of the array arr are printed. A code snippet which demonstrates this is as follows −

int[] arr = {2, 5, 8, 1, 9};
System.out.print("The array elements are: ");
for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
}

After this, the Arrays.fill() method is used to assign the value 9 to all the elements in the array arr. Then this array is printed. A code snippet which demonstrates this is as follows −

Arrays.fill(arr, 9);
System.out.print("\nThe array elements after Arrays.fill() method are: ");
for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
}
raja
Published on 09-Jan-2019 11:29:04
Advertisements