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.

public class Employee
{
  int salary = 1000;
  public static void main(String args[])
  {
    Employee emp[] = new Employee[10];
    // System.out.println(emp[0].salary);  // throws NullPointerException

   for(int i = 0; i < emp.length; i++)
   {
     emp[i] = new Employee();
     System.out.println(emp[i].salary);
   }
  }
}


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

       Employee emp[] = new Employee[10];

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.

       for(int i = 0; i < emp.length; i++)
       {
         emp[i] = new Employee();
         System.out.println(emp[i].salary);
       }

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".

6 thoughts on “Create Array Objects”

  1. How to access aarya of object in another class. I m trying to make assignment to get information in a single array from two different classes and want to print in another class but it printing NULL . Why is it so? Please help me out.!!

Leave a Comment

Your email address will not be published.