Array Of Objects In Java

In the Java programming language, an array is a data structure that can hold multiple elements of the same data type. Arrays in Java are capable of dynamically creating objects and can store elements of primitive types. Java provides the functionality to store objects within an array.

A collection of multiple objects stored in one variable is known as an array of objects. This type of array contains references to the individual objects, making it a practical solution for efficiently handling multiple instances of a class.

Creating an Array of Objects

Prior to constructing an array of objects, it is necessary to instantiate the class using the new keyword. Various statements can be utilized to generate an array of objects.

Syntax:

Example

ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects
Example

ClassName[] objArray;
Example

ClassName objeArray[];

Imagine a scenario where a class called Employee has been established. The objective is to maintain information on 20 employees within a company divided into three departments. Rather than generating 20 distinct variables, an array of objects will be generated, as illustrated below.

Example

Employee department1[20];

Employee department2[20];

Employee department3[20];

The statements above initialize an array consisting of 20 objects.

Example: Creating an Array of Objects

Within the code snippet below, a class called Product has been defined, and an array of objects has been instantiated through the constructor. The Product class includes a constructor with parameters for product ID and product name. Within the main function, distinct instances of the Product class have been instantiated, and initial values have been assigned to each object via the constructor.

Example

Example

public class Main  {  

    public static void main(String args[])   {  

        //create an array of product objects   

        Product[] obj = new Product[5] ;  

        //create & initialize actual product objects using constructor  

        obj[0] = new Product(23907,"Dell Laptop");  

        obj[1] = new Product(91240,"HP 630");  

        obj[2] = new Product(29823,"LG OLED TV");  

        obj[3] = new Product(11908,"MI Note Pro Max 9");  

        obj[4] = new Product(43590,"Kingston USB");  

        //display the product object data  

        System. out.println("Product Object 1:");  

        obj[0].display();  

        System.out.println("Product Object 2:");  

        obj[1].display();  

        System.out.println("Product Object 3:");  

        obj[2].display();  

        System.out.println("Product Object 4:");  

        obj[3].display();  

        System.out.println("Product Object 5:");  

        obj[4].display();  

    }  

}  

 //Product class with product ID and product name as attributes  

class Product  {  

    int pro_Id;  

    String pro_name;  

    //Product class constructor  

    Product(int pid, String n)  {  

        pro_Id = pid;  

        pro_name = n;  

    }  	

    public void display()  {  

        System.out.print("Product ID = "+pro_ID + "  " + " Product Name = "+pro_name);  

        System.out.println();  

    }  

}

Output:

Output

Product Object 1:

Product ID = 23907 Product Name = Dell Laptop

Product Object 2:

Product ID = 91240 Product Name = HP 630

Product Object 3:

Product ID = 29823 Product Name = LG OLED TV

Product Object 4:

Product ID = 11908 Product Name = MI Note Pro Max 9

Product Object 5:

Product ID = 43590 Product Name = Kingston USB

Initializing an Array of Objects

Once the objects have been created, it is essential to initialize the array with values. Unlike primitive types, initializing an array of objects requires individual initialization of each element or object within the array. The array stores references to the actual objects of the class.

It is advisable to create instances of a class after initializing an array of objects. The constructors are responsible for initializing the array. The application can assign initial values to the actual objects by providing values to the constructor. Alternatively, a standalone member method of the class can also be utilized to assign data to an object.

Initializing the elements of an array of objects is essential after their creation. There are two common methods to achieve this:

  • Initialization via the Constructor
  • Initialization using Setter Methods
  • 1. Using the Constructor

By passing individual variables to the constructor, we can set initial values for each object during its creation, ensuring that each object is instantiated with distinctive values.

Example

Example

// Java program to demonstrate initializing an array of objects using a constructor

public class Main {

    public static void main(String args[]) {

        // Declaring an array of Book

        Book[] books;

        // Allocating memory for 3 Book objects

        books = new Book[3];

        // Initializing the elements of the array using the constructor

        books[0] = new Book(101, "Java Basics");

        books[1] = new Book(102, "Data Structures");

        books[2] = new Book(103, "Operating Systems");

        System.out.println("Book details:");

        for (int i = 0; i < books.length; i++) {

            books[i].display();

        }

    }

}

// Creating a Book class with id and title as attributes

class Book {

    public int bookId;

    public String title;

    // Book class constructor

    Book(int bookId, String title) {

        this.bookId = bookId;

        this.title = title;

    }

    // display() method to display the book data

    public void display() {

        System.out.println("Book ID: " + bookId + ", Title: " + title);

    }

}

Output:

Output

Book details:

Book ID: 101, Title: Java Basics

Book ID: 102, Title: Data Structures

Book ID: 103, Title: Operating Systems

3. Using Setter Methods

By utilizing setter methods, it is possible to assign values to objects after they have been created. The initial values for the objects are set using a member function specific to the class being instantiated.

Example

Example

// Java program to demonstrate initializing an array of objects using setter methods

public class Main {

    public static void main(String args[]) {

        // Declaring an array of Book

        Book[] books;

        // Allocating memory for 3 objects of type Book

        books = new Book[3];

        // Creating actual Book objects

        books[0] = new Book();

        books[1] = new Book();

        books[2] = new Book();

        // Assigning data to Book objects using the setter method

        books[0].setData(201, "Java Programming");

        books[1].setData(202, "Algorithms");

        books[2].setData(203, "Database Systems");

        // Displaying the book data

        System.out.println("Book details:");

        for (int i = 0; i < books.length; i++) {

            books[i].display();

        }

    }

}

// Creating a Book class with id and title as attributes

class Book {

    public int bookId;

    public String title;

    // Setter method to set the data

    public void setData(int bookId, String title) {

        this.bookId = bookId;

        this.title = title;

    }

    // display() method to show book details

    public void display() {

        System.out.println("Book ID: " + bookId + ", Title: " + title);

    }

}

Output:

Output

Book details:

Book ID: 201, Title: Java Programming

Book ID: 202, Title: Algorithms

Book ID: 203, Title: Database Systems

Important Points to Remember

  • The array stores references to objects, not the actual objects themselves.
  • Objects are created dynamically using the new keyword, while the array holds their references.
  • We can use a loop to access and modify each object.
  • Array of Objects MCQs

  1. What does an array of objects store in Java?
  • Actual objects
  • References to objects
  • Primitive values
  • None of the above

Explanation: In Java, an array of objects stores references to objects, not the actual objects themselves. The objects are created separately using the new keyword.

  1. Which of the following is the correct way to declare an array of objects in Java?
  • Student students = new Student[6];
  • Student students = new Student;
  • Student students = new Student[6];
  • Student students[6] = new Student;

Explanation: The correct syntax for declaring an array of objects is Student students = new Student[5];. This creates an array that can hold references to Student objects.

  1. How do you initialize an array of objects in Java?
  • Student students = new Student[6];
  • Student students = new Student;
  • Student students = new Student[6];
  • Student students = {new Student, new Student};

Explanation: We can initialize an array of objects using {new Student, new Student} or by assigning individual objects to array indices.

  1. An array of objects is created using the __________class.
  • Object
  • Arrays
  • ArrayList
  • None of the above

Explanation: An array of objects is created using the 'Object' class.

  1. What is an array of Objects?
  • An array of objects is a collection of multiple objects stored in a single variable.
  • An array of objects is a collection of single objects stored in a single variable.
  • An array of objects is a collection of multiple objects stored in a multiple variable.
  • An array of objects is a collection of Single objects stored in a Multiple variable.

An array of objects refers to a grouping of several objects that are kept within a solitary variable.

Input Required

This code uses input(). Please provide values below: