logo codesdope

Array of Objects in Java


After having good command over the class and objects, you must have understood how useful the concept of class and objects can be. Now, imagine you are making a task scheduler application and you have made a 'Task' class having elements like date, time and title. Now, you have to store hundreds of tasks. And there you got the need of creating an array of objects like we had done with different data-types.
So, let's learn how to declare an array of objects.

class Car{
  public int power;
  public int Serial_no;
  public Car(int p, int s){
    power = p;
    Serial_no = s;
  }
}

class Ar1{
  public static void main(String[] args){
    Car[] c;
    c = new Car[10];
    c[0] = new Car(800,111);
  }
}
Output

Let's go through this code.
Car[] c; - This line declares that c is an array of 'Car'.
c = new Car[10] - This line will create an array 'c' of 10 elements of class 'Car'.

Here, only an array is created and not objects of 'Car'. To create an object, we need to use the 'new' operator with the 'Car' class.
c[0] = new Car(800,111); - This line will create an object of 'Car' on 0th element of the array 'c' and assign 800 to power and 111 to serial_no of this object.

array of object in java

I hope you are now ready to create array of objects.

There are a lot of questions in the practice section of different levels. Do some practice to make your knowledge more concrete.

Don't practice until you get it right. Practice until you can't get it wrong.

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.