Filling array elements fill() method

Filling array elements fill() method

Arrays.fill() is useful to fill an array with one value. After this method call, all the elements of the array will have the same value.

Two methods exist to do the job with Arrays class; the first one fills all the array elements and the second one fills a few (not complete array). Following are the method signatures.

  1. static void fill(int array1[], int num): Useful to fill the array array1 with the same element num. After this method call, all the elements are of the same value. The method is overloaded to take any data type and objects. It is similar to Collections.fill().
  2. static void fill(int array1[], int startIndex, int endIndex, int num): It is a modified form of previous fill() method where a few elements of the array are filled with the same value; from startIndex to endIndex-1 in the array array1. The method is overloaded to accept arrays with different data types and objects. It is equivalent to Collections.fill().
Example on Filling array elements fill() method uses both the above methods


Filling array elements fill() method
Output screenshot on Filling array elements fill() method

String names1[] = new String[5];
System.out.println(“names1 elements before fill: ” + Arrays.toString(names1));

A string array names1 is created with 5 elements. The unassigned string elements are assigned with null values by default, as Java does not support garbage values. The elements are printed with toString() method of Arrays class.

Arrays.fill(names1, “java”);

Now all the null values of names1 are replaced with "java". Observe the screenshot; all the 5 elements are filled with "java".

Arrays.fill(names1, 1, 4, “robust”);

The previous fill() is used when all the elements in an array requires replacement. The overloaded fill() is used to fill (actually it is replacement) a few elements. The elements 1, 2, and 3 (4-1) are replaced with "robust" word. Observe the screenshot.

It is equivalent to Collections.fill() that operates on data structure elements.

Leave a Reply

Your email address will not be published. Required fields are marked *