Array of objects in Java: Java is an object-oriented programming language (OOPs) that uses objects and classes. If there is only a single object, then one variable is enough to store it. However, when you have more than one object, an array object will be helpful to store numerous array of objects in Java.Â
In this article, we will learn how to declare, implement and use an array of objects in Java with the help of suitable examples.
Learn Java Programming with PW Skills
Join our Decode Java Programming with DSA course to master Java programming along with Data structures and Algorithms. This complete course is covered by experts from industries providing important insights to make you job-ready.
Also, get perks like doubt-solving sessions, industry-relevant projects, Free online compiler PW Lab, course completion certificate, 100% placement assistance, and much more. Know more about this course at @pwskills.com
What is an Array of Objects in Java?
Array in Java is an array where each element is an object rather than a primitive data type. In a Java array, we do not store integers, characters or other primitive data types, rather we store instances of an object or classes.Â
Also, remember, when we say ‘array of objects’ it does not mean that arrays store actual objects. Rather, it stores references to objects inside. Let us learn more about an array of objects in this article.
Recommended Technical Course
- Full Stack Development Course
- Generative AI Course
- DSA C++ Course
- Data Analytics Course
- Python DSA Course
- DSA Java Course
Array of Objects in Java: Steps to Create an Array of Objects?
We can create an array of objects using any of the syntax given below.
Array of Objects in Java |
ClassName [ ] object_Name =Â new ClassName [ length of Array]; |
Or you can use the syntax below to create an array object in Java.
Array of Objects in Java |
ClassName object_Name [ ] =Â new ClassName [ length of Array]; |
Remember, we must create an instance of class before creating an array of objects. The objects in the array are the reference to the objects defined in the class.
Also Read: AWT In Java: Examples, Hierarchy & Methods
Array of Objects in Java: Examples
Let us create an array of objects having the Id number and name of the person.Â
Array of Objects in Java |
public class ArrayOfObjects {
    public static void main(String args[]) {         // create an array of Person objects         Person[] peopleArray = new Person[3];         // create & initialize actual Person objects using constructor         peopleArray[0] = new Person(“Alice”, 25);         peopleArray[1] = new Person(“Bob”, 30);         peopleArray[2] = new Person(“Charlie”, 22);         // display the Person object data         System.out.println(“Person Object 1:”);         peopleArray[0].display();         System.out.println(“Person Object 2:”);         peopleArray[1].display();         System.out.println(“Person Object 3:”);         peopleArray[2].display();     } } // Person class with name and age as attributes class Person {     String name;     int age;     // Person class constructor     Person(String name, int age) {         this.name = name;         this.age = age;     }     public void display() {         System.out.print(“Name = ” + name + ” ” + ” Age = ” + age);         System.out.println();     } } |
Output
Check the output of the given program consisting of array of objects having different values.
Person Object 1:
Name = Alice Age = 25 Person Object 2: Name = Bob Age = 30 Person Object 3: Name =Â Charlie Age = 22 |
Array of Objects in Java: IntiliaiziationÂ
Unlike primitive arrays, which consist of data types such as integer, float, char, etc. Array in Java consists of a reference of objects that needs to be initialized after declaration. Allocate memory for the array using the ‘new’ keyword and initialize individual elements by creating instances of objects and assigning them to the array of objects in Java.Â
- First, we need to declare and create an array of person objects.
Array of Objects in Java |
// Creating and declaring array of objects in Java
  Person[ ] peopleArray = new Person[3];  |
- In the case of Java arrays, we need to initialize each array element in Java. Now, let us intialize individual elements for the array of objects.
Array of Objects in Java |
 peopleArray[0] = new Person(“Alice”, 25);
   peopleArray[1] = new Person(“Bob”, 30);    peopleArray[2] = new Person(“Charlie”, 22); |
After initialization of arrays of objects in Java using constructors. If you create objects, you can easily initialize values for each object by passing values directly using the constructor.
Also Read: Armstrong Number In Java: Everthing You Need to Know
Array of Objects in Java: Different Ways to InitializeÂ
There are two major methods to intialize an array of objects in Java. The first one, which is more frequently used, is using constructors, and the second option is using the separate member method.
1. Initialize Array of Objects Using Constructor
We can initialize arrays in Java using constructors. We only pass the values of objects using the constructor. Constructor methods are more frequently used to intialize an array of objects. Check an example where we initialize three students using constructor method.
Array of Objects in Java: Using Constructor |
 public class ArrayOfObjectsInitialization {
    public static void main(String[] args) {    // Create an array of Student objects using a constructor        Student[] studentsArray1 = {             new Student(“John”, 21),             new Student(“Alice”, 22),             new Student(“Bob”, 20)         };         // Display the initialized objects         System.out.println(“Initialized using constructor:”);         for (Student student : studentsArray1) {             student.display();         }     // Student class with a constructor     static class Student {         String name;         int age;         // Constructor to initialize Student objects         public Student(String name, int age) {             this.name = name;             this.age = age;         }         // Display method to print the attributes of a Student object         public void display() {             System.out.println(“Name = ” + name + “, Age = ” + age);         }     } } |
2. Initialize Array of Objects using Member Method
Now, if we want to create an employee class having their name and age using member method. Then check the table below.
Array of Objects in Java: using separate member method |
// Create an array of Employee objects and initialize using a separate member method
        Employee[] employeesArray = new Employee[3];         initializeEmployees(employeesArray);         // Display the initialized objects         System.out.println(“\nInitialized using a separate member method:”);         for (Employee employee : employeesArray) {             employee.display(); //using loops to display employes values.         }     }  // Employee class with a member method for initialization     static class Employee {         String name;         int age;         // Member method to initialize Employee objects         public void initialize(String name, int age) {             this.name = name;             this.age = age;         }         // Display method to print the attributes of an Employee object         public void display() {             System.out.println(“Name = ” + name + “, Age = ” + age);         }     }     // Member method to initialize an array of Employee objects     static void initializeEmployees(Employee[] employees) {         employees[0] = new Employee();         employees[0].initialize(“John”, 25);         employees[1] = new Employee();         employees[1].initialize(“Alice”, 30);         employees[2] = new Employee();         employees[2].initialize(“Bob”, 22);     } } |
Also Read: How to Get Input From Users in Java?
Array of Objects: Which is better Constructor or Separate Member method?
Highlighting some of the important features of the Constructor and separate member method in the table below.
Array of Object: Important Highlights | |
Constructor Method | Separate Member Method |
It allows for concise and readable object creation. | It provides flexibility during the initialization of object arrays. |
The attributes of the object class are immutable and cannot be changed once created. | We can change attributes or values using member methods easily. |
It does not provide much control and is not flexible and dynamic. | It provides greater control to developers. |
Lazy initialization is not supported using a constructor. Objects are initialized during creation. | You can implement lazy initialization with separate member methods as some of the attributes or parameters can be initialized as per use. |
However, both methods are efficient and can be used as per needs. The first one using constructors, is easy to implement. However, separate member methods give good flexibility and control.
For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group
Array of Objects in Java FAQs
What is an array of objects in Java?
Array in Java is an array where each element is an object rather than a primitive data type. In a Java array, we do not store integers, characters or other primitive data types, rather we store instances of an object or classes.
Are there actual objects stored in java arrays?
No, the array of objects in Java consists of references to the objects not actual objects stored inside.
How to get data from an array of objects in Java?
We can get values from an array in Java using the get () method. It returns the value of the components on the particular index.
How to print an array of objects in Java?
We can easily print the array of object values using the toString() method in Java, which converts the array into strings that can be easily printed using the System.out method.