Java Program to fill elements in an int array

Java 8Object Oriented ProgrammingProgramming

Elements can be filled in an int array using the java.util.Arrays.fill() method. This method assigns the required int value to the int array in Java. The two parameters required are the array name 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[5];
      int intValue = 9;
      Arrays.fill(intArray, intValue);
      System.out.println("The int array content is: " + Arrays.toString(intArray));
   }
}

Output

The int array content is: [9, 9, 9, 9, 9]

Now let us understand the above program.

First the int array intArray[] is defined. Then the value 9 is filled in the int array using the Arrays.fill() method. Finally, the int array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

int[] intArray = new int[5];
int intValue = 9;
Arrays.fill(intArray, intValue);
System.out.println("The int array content is: " + Arrays.toString(intArray));
raja
Published on 09-Jan-2019 16:24:41
Advertisements