Fill elements in a Java long array in a specified range

Java 8Object Oriented ProgrammingProgramming

Elements can be filled in a Java long array in a specified range using the java.util.Arrays.fill() method. This method assigns the required long value in the specified range to the long 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 {
      long[] longArray = new long[10];
      long longValue = 95;
      int indexStart = 1;
      int indexFinish = 6;
      Arrays.fill(longArray, indexStart, indexFinish, longValue);
      System.out.println("The long array content is: " + Arrays.toString(longArray));
   }
}

Output

The long array content is: [0, 95, 95, 95, 95, 95, 0, 0, 0, 0]

Now let us understand the above program.

First the long array longArray[] is defined. Then the the Arrays.fill() method is used to fill the long array with value 95 from index 1(inclusive) to index 6(exclusive). Finally, the long array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

long[] longArray = new long[10];
long longValue = 95;
int indexStart = 1;
int indexFinish = 6;
Arrays.fill(longArray, indexStart, indexFinish, longValue);
System.out.println("The long array content is: " + Arrays.toString(longArray));
raja
Published on 11-Jan-2019 10:47:45
Advertisements