0% found this document useful (0 votes)
22 views10 pages

Skip To Content3

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Skip To Content3

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
Arrays in Java
Arrays class in Java
Multidimensional Arrays in Java
Different Ways To Declare And Initialize 2-D Array in Java
Jagged Array in Java
Final Arrays in Java
Reflection Array Class in Java
util.Arrays vs reflect.Array in Java with Examples
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Reflection Array Class in Java
Last Updated : 06 Aug, 2024
The Array class in java.lang.reflect package is a part of the Java Reflection. This
class provides static methods to create and access Java arrays dynamically. It is a
final class, which means it can’t be instantiated or changed. Only the methods of
this class can be used by the class name itself.

The java.util.Arrays class contains various methods for manipulating arrays (such
as sorting and searching), whereas this java.lang.reflect.Array class provides
static methods to create and access Java arrays dynamically. This Array class keeps
the array to be type-safe.

Class Hierarchy
java.lang.Object
↳ java.lang.reflect.Array
Class Declaration
public final class Array
Note: The Array class should be correctly represented as public final class Array.
It extends Object implicitly but does not explicitly declare extends Object.

Syntax to use Array:


Array.<function name>;
Methods in Reflection Array Class in Java
S. No. Method Description
1 Object get(Object array, int index) This method returns the value of the
indexed component in the specified array object.
2 boolean getBoolean(Object array, int index) This method returns the value
of the indexed component in the specified array object as a boolean.
3 byte getByte(Object array, int index) This method returns the value of
the indexed component in the specified array object as a byte.
4 char getChar(Object array, int index) This method returns the value of
the indexed component in the specified array object as a char.
5 double getDouble(Object array, int index) This method returns the value of
the indexed component in the specified array object as a double.
6 float getFloat(Object array, int index) This method returns the value of
the indexed component in the specified array object as a float.
7 int getInt(Object array, int index) This method returns the value of the
indexed component in the specified array object as an int.
8 int getLength(Object array) This method returns the length of the specified
array object as an int.
9 long getLong(Object array, int index) This method returns the value of
the indexed component in the specified array object as a long.
10 short getShort(Object array, int index) This method returns the value of
the indexed component in the specified array object as a short.
11 Object newInstance(Class<E> componentType, int length) This method
creates a new array with the specified component type and length.
12 Object newInstance(Class<E> componentType, int… dimensions)This method
creates a new array with the specified component type and dimensions.
13 void set(Object array, int index, Object value) This method sets the value of
the indexed component of the specified array object to the specified new value.
14 void setBoolean(Object array, int index, boolean z) This method sets the
value of the indexed component of the specified array object to the specified
boolean value.
15 void setByte(Object array, int index, byte b) This method sets the value of
the indexed component of the specified array object to the specified byte value.
16 void setChar(Object array, int index, char c) This method sets the value of
the indexed component of the specified array object to the specified char value.
17 void setDouble(Object array, int index, double d) This method sets the
value of the indexed component of the specified array object to the specified
double value.
18 void setFloat(Object array, int index, float f) This method sets the value of
the indexed component of the specified array object to the specified float value.
19 void setInt(Object array, int index, int i) This method sets the value of
the indexed component of the specified array object to the specified int value.
20 void setLong(Object array, int index, long l) This method sets the value of
the indexed component of the specified array object to the specified long value.
21 void setShort(Object array, int index, short s) This method sets the value of
the indexed component of the specified array object to the specified short value.
How to create an Array using java.lang.reflect.Array Class?
Creating an array using reflect.Array Class is different from the usual way. The
process to create such an array is as follows:

Get the size of the array to be created


To create an array (say of X class), use the newInstance() method of Array class to
pass the X class as the type of the array, and the size of the array, as
parameters.
Syntax:

X[] arrayOfXType = (X[]) Array.newInstance(X.class, size);


Where X is to be replaced by the type of the array like int, double, etc.

This method returns an Object array of the given size, then cast into the required
X[] type.
Hence the required array of type X has been created.
Below is an example to create an integer array of size 5, using the Array class:

Example: To create an integer array of size 5:

// Java code to create an integer array of size 5,


// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {


public static void main(String[] args)
{

// Get the size of the array


int sizeOfArray = 5;

// Create an integer array


// using reflect.Array class
// This is done using the newInstance() method
int[] intArray = (int[])Array.newInstance(
int.class, sizeOfArray);

// Printing the Array content


System.out.println(Arrays.toString(intArray));
}
}

Output
[0, 0, 0, 0, 0]
How to add elements in an Array using java.lang.reflect.Array Class?
Like creating an array, adding elements in the array using reflect.Array Class is
also different from the usual way. The process to add elements in such an array is
as follows:

Get the value of the element to be added.


Get the index at which the element is to be added.
To add an element in an array (say of X class), use the setX() method of Array
class, where X is to be replaced by the type of the array such as setInt(),
setDouble(), etc. This method takes the X[] as the first parameter, the index at
which the element is added as the second parameter, and the element as the third
parameter in the below syntax.
Syntax:

Array.setX(X[], indexOfInsertion, elementToBeInserted);


Where X is to be replaced by the type of the array like int, double, etc.

This method inserts the element at the specified index in this array.
Hence the required element has been inserted into the array.
Below is an example to add an element into an integer array, using the Array class:

Example: To add an element into an integer array:

// Java code to add an element into an integer array,


// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {


public static void main(String[] args)
{

// Get the size of the array


int sizeOfArray = 3;

// Create an integer array


// using reflect.Array class
// This is done using the newInstance() method
int[] intArray = (int[])Array.newInstance(
int.class, sizeOfArray);

// Add elements to the array


// This is done using the setInt() method
Array.setInt(intArray, 0, 10);
Array.setInt(intArray, 1, 20);
Array.setInt(intArray, 2, 30);
// Printing the Array content
System.out.println(Arrays.toString(intArray));
}
}

Output
[10, 20, 30]
How to retrieve elements in an Array using java.lang.reflect.Array Class?
Like creating an array, retrieving elements in the array using reflect.Array Class
is also different from the usual way. The process to retrieve elements in such an
array is as follows:

Get the index at which the element is to be retrieved.


To retrieve an element in an array (say of X class), use the getX() method of Array
class, where X is to be replaced by the type of the array such as getInt(),
getDouble(), etc. This method takes the X[] as the first parameter and the index at
which the element is retrieved as the second parameter in the syntax below.
Syntax:

Array.getX(X[], indexOfRetrieval);
Where X is to be replaced by the type of the array like int, double, etc.

This method retrieves the element at the specified index from this array.
Hence the required element has been retrieved from the array.
Below is an example to retrieve an element from an integer array using the Array
class:

Example: To retrieve an element from an integer array:

// Java code to retrieve an element from an integer array,


// using the Array class:

import java.lang.reflect.Array;
import java.util.Arrays;

public class GfG {


public static void main(String[] args)
{

// Get the size of the array


int sizeOfArray = 3;

// Create an integer array


// using reflect.Array class
// This is done using the newInstance() method
int[] intArray = (int[])Array.newInstance(
int.class, sizeOfArray);

// Add elements to the array


// This is done using the setInt() method
Array.setInt(intArray, 0, 10);
Array.setInt(intArray, 1, 20);
Array.setInt(intArray, 2, 30);

// Printing the Array content


System.out.println(Arrays.toString(intArray));

// Retrieve elements from the array


// This is done using the getInt() method
System.out.println("Element at index 0: "
+ Array.getInt(intArray, 0));
System.out.println("Element at index 1: "
+ Array.getInt(intArray, 1));
System.out.println("Element at index 2: "
+ Array.getInt(intArray, 2));
}
}

Output
[10, 20, 30]
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

RishabhPrabhu

19
Previous Article
Final Arrays in Java
Next Article
util.Arrays vs reflect.Array in Java with Examples
Read More
Down Arrow
Similar Reads
How to call private method from another class in Java with help of Reflection API?
We can call the private method of a class from another class in Java (which is
defined using the private access modifier in Java). We can do this by changing the
runtime behavior of the class by using some predefined methods of Java. For
accessing private methods of different classes we will use Reflection API. To call
the private method, we will u
3 min read
Reflection in Java
Reflection is an API that is used to examine or modify the behavior of methods,
classes, and interfaces at runtime. The required classes for reflection are
provided under java.lang.reflect package which is essential in order to understand
reflection. So we are illustrating the package with visual aids to have a better
understanding as follows: Refl
5 min read
How to Invoke Method by Name in Java Dynamically Using Reflection?
Java Reflection API provides us information about a Class to which the Object
belongs to including the methods in this class. Using these Reflection API we would
be able to get invoking pointer for a method in a class with its name. There are
two functions used for this purpose: Invoking method with its nameFinding a method
by Name in a class and i
4 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts
can break the singleton property of a class and how to avoid them. There are mainly
3 concepts that can break the singleton property of a class. Let's discuss them one
by one. Reflection: Reflection can be caused to destroy singleton property of the
singleton class,
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class
Class represent classes and interfaces in a running Java application. The primitive
Java types (boolean, byte, char, short, int, long, float, and double), and the
keyword void are also represented as Class objects. It has no public constructor.
Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This
method returns the Java language modifiers for this class or interface, encoded in
an integer. The modifiers consist of the Java Virtual Machine's constants for
public, protected, private, final, static, abstract and interface. These modifiers
are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and
java.sql.Date in many instances. Whenever the java application interacts with the
database, we should use these instead of java.util.Date. The reason is JDBC i.e.
java database connectivity uses these to identify SQL Date and Timestamp. Here let
us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article
Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone
class we can get the time difference in term of hour and minute between two
places.Problem : How we can get time difference of time in terms of hours and
minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use
the Pair class provided by the library and create a new Unit class that extends the
Unit class provided by the library. Here is an example implementation: Here is an
example Java code that uses the MyPair class with MyUnit and displays the output:
Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct
values import java.util.*; import org.javatuples.*; class GfG { public static void
main(String[] args) { // create Pair Pair&lt;Integer, String&gt; pair = new
Pair&lt;Integer, String&gt;( Integer.valueOf(1), &quot;GeeksforGeeks&quot;); //
Print the Pair System.out.printl
2 min read
Article Tags :
Java
Java-Class and Object
java-reflection-array
Practice Tags :
Java
Java-Class and Object
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like