Just like with primitive data types, arrays, in Java, can be created with objects. Infact, objects are reference types. In the following program, Student objects arrays are created in different styles and their values are printed. Example on Objects Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
public class Student { int marks; public static void main(String args[]) { Student std1[] = new Student[3]; // creating array of Student reference variables // std1[0].marks = 40; // raises NullPointerException std1[0] = new Student(); // converting each student reference varaibles into Student object std1[1] = new Student(); std1[2] = new Student(); std1[0].marks = 40; // assigning values std1[1].marks = 50; std1[2].marks = 60; System.out.println(std1[0].marks); // prints 40 System.out.println(std1[1].marks); // prints 50 System.out.println(std1[2].marks); // prints 60 // this can be done like this also in a loop Student std2[] = new Student[3]; // creating array of Student reference variables int x = 70; for(int i = 0; i < std2.length; i++, x+=10) // converting reference variables into objects in a loop { std2[i] = new Student(); std2[i].marks = x; // assign some marks in loop itself } for(int i = 0; i < std2.length; i++) // print the value in a loop { System.out.println(std2[i].marks); // prints 70, 80, 90 } // this can be done like this also Student std3 = new Student(); std3.marks = 45; Student std4 = new Student(); std4.marks = 55; Student std5 = new Student(); std5.marks = 65; Student std6[] = {std3, std4, std5}; for(int i = 0; i < std6.length; i++) // print the value in a loop { System.out.println(std6[i].marks); // prints 45, 55, 65 } // this can be done like this also; storing anonymous objects in the array Student std7[] = {new Student(), new Student(), new Student()}; std7[0].marks = 66; std7[1].marks = 76; std7[2].marks = 86; for(int i = 0; i < std7.length; i++) // print the value in a loop { System.out.println(std7[i].marks); // prints 66, 76, 86 } } } |
Student std1[] = new Student[3]; // creating array of…