Simple Class and Array of Object Example in Java
Introduction
Simple Class and Array of Object is a classic Java console program that demonstrates the concept with complete source code and sample output. These programs cover your first Java class, constructors, methods and simple OOP building blocks.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
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 : 29When to use
Use this simple class and array of object example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
Employee[] employees = new Employee[3];updates a variable used in the calculation or output. -
Employee employee1 = new Employee("Ramesh", 25);updates a variable used in the calculation or output. -
Employee employee2 = new Employee("Suresh", 21);updates a variable used in the calculation or output. -
Employee employee3 = new Employee("Ganesh", 29);updates a variable used in the calculation or output. -
employees[0] = employee1;updates a variable used in the calculation or output. -
employees[1] = employee2;updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.