Objects Array in Java

Objects Array in Java

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

Student std1[] = new Student[3]; // creating array of Student reference variables
// std1[0].marks = 40; // raises NullPointerException

In the above statement, many think that std1[] is an array with 3 Student objects. No, not at all. std1[] is an array with 3 Student reference variables. That is, you have created an array of 3 reference variables. std1[0].marks = 40; gives NullPointerException as std1[0] is a reference variable and not object. std1[0] should be converted into an object and then used. It is done in the next statement.

std1[0] = new Student(); // converting each student reference

In the above statement, std1[0] is converted into object just like any other by calling Student constructor with new keyword. Like this, each array element should be converted into Student object.

Student std2[] = new Student[3];

Just for a change, again std2[] array of 3 reference variables is created. Each reference variable is converted into object in a for loop and in the same for loop values are also assigned.

Student std6[] = {std3, std4, std5};

In the above statement, std6[] array contains real objects.

Student std7[] = {new Student(), new Student(), new Student()};
std7[0].marks = 66;
std7[1].marks = 76;
std7[2].marks = 86;

Now std7[] is a Student array with 3 anonymous objects Student. std7[0] contains first Student anonymous objects. Marks are assigned.

Shall we go a little deeper into Objects Array. Observe the following code. Before going into the notes, think yourself how the program works.

Object obj1[] = {new Student(), new Employee(), new Officer()};

We know an array stores similar types. But the above array obj1 stores dissimilar objects of Student, Employee and Officer. How it is possible?

Object is the root class of all classes of Java. The rule says, a subclass object can be assigned to a super class object implicitly. By this rule, Student object, Employee object and Officer object are implicitly converted to Object class.

Student std1 = (Student) obj1[0];

obj1[0], the first element of Object array obj1 represents internally a Student object. To get back, the Student object from the Object, explicit cast it to Student. That is what is done in the above statement. As proof of conversion, we calling Student class marks with Student object std1. Similarly with Employee and Officer classes.

Leave a Reply

Your email address will not be published. Required fields are marked *