- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create integer array with Array.newInstance in Java
The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method forms a new array with the component type and length as specified in the arguments
Declaration − The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method is declared as follows -
public static Object newInstance(Class<?> componentType, int length) throws IllegalArgumentException, NegativeArraySizeException
Let us see a program to create an integer array with Array.newInstance with Java Reflection -
Example
import java.lang.reflect.Array; public class Example { public static void main(String[] args) { int[] arr = (int[]) Array.newInstance(int.class, 3); // creates a new array Array.set(arr, 0, 5); Array.set(arr, 1, 9); Array.set(arr, 2, 2); System.out.println("Element 1 = " + Array.get(arr, 0)); System.out.println("Element 2 = " + Array.get(arr, 1)); System.out.println("Element 3 = " + Array.get(arr, 2)); } }
Output
Element 1 = 5 Element 2 = 9 Element 3 = 2
Advertisements
To Continue Learning Please Login
Login with Google