
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Reflection to Create, Fill and Display an Array in Java
An array is created using the java.lang.reflect.Array.newInstance() method. This method basically creates a new array with the required component type as well as length.
The array is filled using the java.lang.reflect.Array.setInt() method. This method sets the required integer value at the index specified for the array.
The array displayed using the for loop. A program that demonstrates this is given as follows −
Example
import java.lang.reflect.Array; public class Demo { public static void main (String args[]) { int arr[] = (int[])Array.newInstance(int.class, 10); int size = Array.getLength(arr); for (int i = 0; i<size; i++) { Array.setInt(arr, i, i+1); } System.out.print("The array elements are: "); for(int i: (int[]) arr) { System.out.print(i + " "); } } }
The output of the above program is as follows −
The array elements are: 1 2 3 4 5 6 7 8 9 10
Now let us understand the above program.
The array is created using the Array.newInstance() method. Then a for loop and the Array.setInt() method are used to fill the array. A code snippet which demonstrates this is as follows −
int arr[] = (int[])Array.newInstance(int.class, 10); int size = Array.getLength(arr); for (int i=0; i<size; i++) { Array.setInt(arr, i, i+1); }
The array is displayed using a for loop. A code snippet which demonstrates this is as follows −
System.out.print("The array elements are: "); for(int i: (int[]) arr) { System.out.print(i + " "); }