Fill elements in a Java int array in a specified range


Elements can be filled in a Java int array in a specified range using the java.util.Arrays.fill() method. This method assigns the required int value in the specified range to the int array in Java.

The parameters required for the Arrays.fill() method are the array name, the index of the first element to be filled(inclusive), the index of the last element to be filled(exclusive) and the value that is to be stored in the array elements.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] argv) throws Exception {
      int[] intArray = new int[10];
      int intValue = 7;
      int indexStart = 2;
      int indexFinish = 8;
      Arrays.fill(intArray, indexStart, indexFinish, intValue);
      System.out.println("The int array content is: " + Arrays.toString(intArray));
   }
}

Output

The int array content is: [0, 0, 7, 7, 7, 7, 7, 7, 0, 0]

Now let us understand the above program.

First, the int array intArray[] is defined. Then the Arrays.fill() method is used to fill the int array with value 7 from index 2(inclusive) to index 8(exclusive). Finally, the int array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

int[] intArray = new int[10];
int intValue = 7;
int indexStart = 2;
int indexFinish = 8;
Arrays.fill(intArray, indexStart, indexFinish, intValue);
System.out.println("The int array content is: " + Arrays.toString(intArray));

Updated on: 30-Jul-2019

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements