×

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

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.