×

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

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes 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.