Create Array Objects

Create Array Objects


Create Array Objects

Summary: Here in this tutorial "Create Array Objects", learn creating an array objects and using them with Java syntax.

Sometimes it is required to create a number of objects for our class in the coding. Creating one by one is laborious. Alternatively, we can go for an array of objects which are created at a time in a single stroke. Here, a small precaution is to be taken with objects and object references.

Following program on "Create Array Objects" illustrates.


Create Array Objects
Output screen of Employee.java of Create Array Objects

The above statement creates an array of Employee references but not objects. A reference variable cannot work like an object until it is converted into an object.

System.out.println(emp[0].salary);

The emp[0] reference does not point any object. For this reason, the above statement raises java.lang.NullPointerException at runtime.

In a for loop, each reference variable of the array is converted into an object as usual with new keyword; instead of creating one by one object individually (just for time saving). Now calling emp[i].salary does not raise any exception as emp[i] is an object.

Pass your comments on the improvement of this tutorial "Create Array Objects".

3 thoughts on “Create Array Objects

Leave a Reply

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