Arrays of Objects in Java


An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location.

Syntax :
   Class_name object [ ] = new class_name ( ) ;

Example :
   Student s [ 5 ] = new Student ( ) ;

This program demonstrates the creation of an array of objects in Java.

  • First, a Student class is defined which has two member variables, roll_no and name, and a constructor that initializes these variables. The Student class also has a print() method that prints out the name and roll_no.
  • Then, in the main() method, an array o of type Student is declared and initialized with a length of 5. Five Student objects are then created and assigned to the elements of the o array using the new keyword and the Student constructor.
  • Finally, a for loop is used to iterate through the o array and call the print() method on each Student object, which prints out the name and roll_no of each student.

Source Code

//Array of Objects in Java
class Student
{
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
    void print()
    {
        System.out.println("Name    : "+name);
        System.out.println("Roll No : "+roll_no);
        System.out.println("---------------------------------");
    }
}
public class array_objects {
    public static void main (String[] args)
    {
        Student[] o;
        o = new Student[5];
        o[0] = new Student(10,"Ram");
        o[1] = new Student(20,"Sam");
        o[2] = new Student(30,"Ravi");
        o[3] = new Student(40,"Kumar");
        o[4] = new Student(50,"Sundar");
        for (int i = 0; i < o.length; i++)
            o[i].print();
    }
}
 

Output

Name    : Ram
Roll No : 10
---------------------------------
Name    : Sam
Roll No : 20
---------------------------------
Name    : Ravi
Roll No : 30
---------------------------------
Name    : Kumar
Roll No : 40
---------------------------------
Name    : Sundar
Roll No : 50
---------------------------------
To download raw file Click Here

Basic Programs