Fill elements in a Java double array in a specified range


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

Output

The double array content is: [0.0, 0.0, 0.0, 2.7, 2.7, 2.7, 2.7, 2.7, 0.0, 0.0]

Now let us understand the above program.

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

double[] doubleArray = new double[10];
double doubleValue = 2.7;
int indexStart = 3;
int indexFinish = 8;
Arrays.fill(doubleArray, indexStart, indexFinish, doubleValue);
System.out.println("The double array content is: " + Arrays.toString(doubleArray));

Updated on: 30-Jul-2019

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements