×

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates objects. Java allows us to store data of primitive type, or even objects.

An object is the variable of particular class type. When we want to create a single object, we create it with the help of Object class. However, to create multiple objects, it is preferred to use array of objects. Array of objects as the name suggests, holds the sequence of objects i.e., the objects are stored as array elements.

Note: the Arrays of Objects doesn’t store the object itself, rather it stores the reference of the object.

Creating an array of objects

In order to create an array of objects, we use the Java Object class (root class of all the objects).

Syntax:

Class_name [ ] object_reference ;


OR


Class_name object_reference [ ];

Example:

If we are creating a class Student and we have to store data (stud_id, stud_name,  department_name ) of 30 students of an institute, we can use array of objects. Here, we cannot create 30 different objects, rather we will create the array of objects as:

Student[ ] stud_object;
OR
Student stud_object [ ];

Above code creates array 30 Student class objects.

Along with declaration array of objects need to be instantiated with new keyword.

Instantiating the array of objects:

The syntax to declare and instantiate array of objects is:

Class_name [ ] object_reference = new Class_name [array_length];

Example:

Student [ ] stud_object = new Student [5];

The above statement creates an array of objects named stud_object which can hold 5 object references.

Once the array of object is declared and instantiated, individual elements of array of objects needs to be created using the new keyword.

Initializing the array of objects:

The array of objects holds references to the actual class objects. Therefore, we need to create actual objects of a class after the declaration and instantiation of array of objects.

Unlike the basic initialization primitive type arrays, we initialize each element of our array of objects (i.e. each object reference) using the new keyword.

There are two ways to initialize the array of objects:

  1. Using constructors
  2. Using separate member method

Using constructors:

While creating the individual objects, we can initialize each object by passing values using the constructor.

Example 1:

Let’s consider the below example where we are creating the class Student and initializing the object references using the constructor of the class.

ArrayOfObjects.java

public class ArrayOfObjects{
public static void main(String[] args) {

//creating array of objects with length 3
Student[] stud_object = new Student[3];


//creating and initializing actual objects using constructor
stud_object[0] = new Student(121, "Riya", "Computer");


stud_object[1] = new Student(211, "Sham", "E&TC");


stud_object[2] = new Student(401, "Param", "Civil");


//printing the Student data
System.out.println("\nStudent object 1:");
stud_object[0].display();


System.out.println("\nStudent object 2:");
stud_object[1].display();


System.out.println("\nStudent object 3:");
stud_object[2].display();


}
}


//creating Student class
class Student {
public int stud_id;
public String stud_name;
public String dept_name;


//Student class constructor
Student (int id, String name, String dept){
this.stud_id = id;
this.stud_name = name;
this.dept_name = dept;
}


//method to display student data
public void display(){
System.out.println("Student id: " +stud_id );
System.out.println("Student name: " +stud_name );
System.out.println("Department of student: " +dept_name );




}


}

Output:

How to create array of objects in Java

Using separate member method:

A member function of a class can be used to initialize the individual objects of an array.

Example 2:

Let’s consider an example where we create class Student and a method init_object() to assign values to the individual objects of the array.

public class ArrayOfObjects2{
public static void main(String[] args) {

//creating array of objects with length 2
Student[] stud_object = new Student[2];


//creating actual Student objects 
stud_object[0] = new Student();
stud_object[1] = new Student();


//assigning values to student objects
stud_object[0].init_object(111, "Nirnay", "Computer");
stud_object[1].init_object(301, "Juli", "E&TC");

//printing the Student data
System.out.println("\nStudent object 1:");
stud_object[0].display();


System.out.println("\nStudent object 2:");
stud_object[1].display();



}
}


//creating Student class
class Student {
public int stud_id;
public String stud_name;
public String dept_name;


//methods to assign values to student objects
public void init_object(int id, String name, String dept){
this.stud_id = id;
this.stud_name = name;
this.dept_name = dept;
}


//method to display student data
public void display(){
System.out.println("Student id: " +stud_id );
System.out.println("Student name: " +stud_name );
System.out.println("Department of student: " +dept_name );




}


}

Output:

How to create array of objects in Java

In this way, we have learned how to create array of objects in Java.


Related Topics

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.