Summary: In this programming example, we will learn to create an array of objects in Java.
A class in Java can be interpreted as a user-defined type, hence we can use it as a type to create an array (like an array of primitive types) that will store its objects.
Example:
//Array of Integers int numbers[] = new int[size]; //Array of Objects class_name object_name[] = new class_name[size];
Here is a Java program that create an array of the Student class and output the same:
import java.util.Scanner;
class Student{
public int roll;
public String name;
Student(int roll, String name){
this.roll = roll;
this.name = name;
}
//Override toString() to print object directly
public String toString(){
return "{roll: "+this.roll+", name: "+this.name+"}";
}
}
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Declare Array of class Students
Student stdArray[]= new Student[3];
System.out.println("Enter 3 students details");
for(int i=0; i<3; i++){
//Create a new object of class Student
Student newStudent = new Student(in.nextInt(),in.next());
//Assign the object to the object array
stdArray[i] = newStudent;
}
System.out.println("Students details are:");
for(int i=0; i<3; i++){
//Student.toString() method will be used to output object
System.out.println(stdArray[i]);
}
}
}
Output:
Enter 3 students details 1 Ak 2 AAk 3 Avk Students details are: {roll: 1, name: Ak} {roll: 2, name: AAk} {roll: 3, name: Avk}
In the above program, we have overridden the toString()
method in the Student
class to display object information in a structured format.
The this
keyword in the string ensures that the values corresponding to the current instance is returned.
When we output stdArray[i]
, the data member values of instance at index i
of the array gets printed.
Hope now you can easily create an array of objects in Java. If you have any doubts or suggestion then comment below.