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 ( ) ;

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