Array of Objects Java

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.

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.

Leave a Reply

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