Simple Class and Array of Object Java Example Program


Syntax

<custom_object>[] <array_name> = new <custom_object>[<array_length>];

Simple Class and Array of Object Example Program

public class SimpleClassAndArrayOfObject {
    static Employee[] generateArray(){
        Employee[] employees = new Employee[3];
        
        Employee employee1 = new Employee("Ramesh", 25);
        Employee employee2 = new Employee("Suresh", 21);
        Employee employee3 = new Employee("Ganesh", 29);
        
        employees[0] = employee1;
        employees[1] = employee2;
        employees[2] = employee3;
        
        return employees;
    }
    
    static void printArray(Employee[] employees){
        for (int i = 0; i < employees.length; i++){
            System.out.println(employees[i].name+" : "+employees[i].age);
        }
    }
    
    public static void main(String[] args) {
        Employee[] employees = new Employee[3];
        employees = generateArray();
        System.out.println("The list of employees in format 'name : age' is");
        printArray(employees);
    }
}

class Employee{
    String name;
    int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Sample Output

The list of employees in format 'name : age' is
Ramesh : 25
Suresh : 21
Ganesh : 29