Working with Array.setInt to fill an array in Java

Java 8Object Oriented ProgrammingProgramming

In order to fill an array in Java, we use the Array.setInt() method. The java.lang.reflect.Array.setInt(Object array, int index, int value) method assigns the value of the component with a particular index of the given array object to the specified integer value.

Declaration − The java.lang.reflect.Array.setInt(Object array, int index, int value) is declared as follows -

public static void setInt(Object array, int index, int value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Let us see a program to fill an array in Java using the Array.setInt() method to fill an array in Java -

Example

 Live Demo

import java.lang.reflect.Array;
public class Example {
   public static void main(String[] args) {
      int[] arr = new int[3];
      Array.setInt(arr, 0, 5); // assigning value 5 at index 0
      Array.setInt(arr, 1, 9); // assigning value 9 at index 1
      Array.setInt(arr, 2, 2); // assigning value 2 at index 2
      System.out.println("Element 1 = " + Array.getInt(arr, 0));
      System.out.println("Element 2 = " + Array.getInt(arr, 1));
      System.out.println("Element 3 = " + Array.getInt(arr, 2));
   }
}

Output

Element 1 = 5
Element 2 = 9
Element 3 = 2
raja
Published on 09-Jan-2019 08:37:50
Advertisements