How to fill (initialize at once) an array in Java



Problem Description

How to fill (initialize at once) an array?

Solution

This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and Array.fill(arrayname, starting index, ending index, value) method of Java Util class.

import java.util.*;

public class FillTest {
   public static void main(String args[]) {
      int array[] = new int[6];
      Arrays.fill(array, 100);
      
      for (int i = 0, n = array.length; i < n; i++) {
         System.out.println(array[i]);
      }
      System.out.println();
      Arrays.fill(array, 3, 6, 50);
      
      for (int i = 0, n = array.length; i < n; i++) {
         System.out.println(array[i]);
      }
   }
}

Result

The above code sample will produce the following result.

100
100
100
100
100
100

100
100
100
50
50
50

Another sample example of array filling

import java.util.Arrays;

public class HelloWorld {
   public static void main(String[] args) {
      // initializing int array
      int arr[] = new int[] {1, 6, 3, 2, 9};
      
      // let us print the values
      System.out.println("Actual values: ");
      
      for (int value : arr) {
         System.out.println("Value = " + value);
      } 
      
      // using fill for placing 18
      Arrays.fill(arr, 18);
      
      // let us print the values
      System.out.println("New values after using fill() method: ");
      
      for (int value : arr) {
         System.out.println("Value = " + value);
      }
   }
}

The above code sample will produce the following result.

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
java_arrays.htm
Advertisements