Skip to content

Commit e5cc233

Browse files
committed
Reflect Arrays Concept Added
1 parent 815e002 commit e5cc233

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

arr_reflect.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.lang.reflect.Array;
2+
import java.util.Arrays;
3+
4+
class arr_reflect{
5+
public static void main(String[] a){
6+
// Getting the size of an array first
7+
int size1 = 4;
8+
9+
// Declaring an actual array first
10+
int[] arr1 = (int[])Array.newInstance(int.class, size1);
11+
System.out.println("Array : " + Arrays.toString(arr1));
12+
13+
// Adding some elements to the Array created
14+
Array.setInt(arr1,0,23);
15+
Array.setInt(arr1,1,45);
16+
Array.setInt(arr1,2,66);
17+
Array.setInt(arr1,3,90);
18+
System.out.println("Array after adding some elements : " + Arrays.toString(arr1));
19+
20+
// Retrieving the element from the Array
21+
System.out.println("Retrieving a particular element from the array : " + Array.getInt(arr1,2));
22+
23+
// Some Methods of Reflected Arrays
24+
// 1. get() : This method is used in order to get the value of the element as per the given index in the array
25+
System.out.println("Getting the element of the array using get() method : " + ((int)Array.get(arr1,2)));
26+
27+
// 2. getBoolean() : This method is used to get the value of the specified index in the Boolean Array
28+
boolean arr[] = {true,false,true,false};
29+
System.out.println("Getting the value of element using getBoolean() method : " + Array.getBoolean(arr,1));
30+
31+
// 3. getByte() : This method is used in order to get the value of the element if the data type of array is byte
32+
byte arr2[] = {'a','c','b'};
33+
System.out.println("Getting the value of element using getByte() method : " + Array.getByte(arr2,0));
34+
35+
// 4. getLength() : This method is used to get the length of the array
36+
System.out.println("Length of the first array is : " + Array.getLength(arr));
37+
38+
// 5. set() : This method is used in order to set a particular value of the array's element
39+
System.out.println("Array Before setting the value of its element : \n" + Arrays.toString(arr));
40+
Array.set(arr,2,false);
41+
System.out.println("Array after changing the value of the element : " + Arrays.toString(arr));
42+
}
43+
}

0 commit comments

Comments
 (0)