Array of Objects Java


An array in Java can be created either with any data type or with any object like Student objects, Employee objects, Integer, Date etc. Following example on Array of Objects creates Student array and Integer array.

class Student
{
  int marks;
}
public class ArrayOfObjects
{
  public static void main(String args[])
  {
    Student std[] = new Student[3];   // array of reference variables of Student
    // std[0].marks = 40;             // raises compilation error
    std[0] = new Student();           // convert each reference variable into Student object
    std[1] = new Student();
    std[2] = new Student();

    std[0].marks = 40;                // assign marks to each Student element 
    std[1].marks = 50;
    std[2].marks = 60;

    System.out.println("\n3 students average marks: " + (std[0].marks+std[1].marks+std[2].marks)/3);

                                     // Array of objects of Integer
    Integer price[] = new Integer[5];
    int value = 10;
    for(int i = 0; i < price.length; i++)
    {
      price[i] = new Integer(value+=5);
      System.out.print(price[i] + " ");
    }
  }
}

Array of ObjectsOutput Screenshot on Array of Objects Java

Student std[] = new Student[3];

There is a big programming trap here. The array object std[] is not an array of Student objects but an array of Student reference variables. Each variable should be converted separately into an object. That is, here std[0], std[1] and std[2] are Student reference variables. Without conversion, at this stage, if you do std[0].marks = 40, raises error.

std[0] = new Student();
std[1] = new Student();
std[2] = new Student();

Each reference variable is converted into an object. Now std[0], std[1] and std[2] are Student objects. They can be used as objects anywhere.

std[0].marks = 40;
std[1].marks = 50;
std[2].marks = 60;

Each Student object is assigned with marks.

Integer price[] = new Integer[5];

Same story here also, you have created 5 reference variables of Integer. That is, each element is a reference variable of Integer class.

for(int i = 0; i < price.length; i++) { price[i] = new Integer(value+=5); System.out.print(price[i] + " "); }

Instead of converting separately each element, a shortcut is using an array (if you do like Student, it takes 5 separate statements).

1. Another example on the same subject is available at Creating Array Objects

2. Java Differences on 90 Topics is given for indepth knowledge on different topics.

1 thought on “Array of Objects Java”

Leave a Comment

Your email address will not be published.