Using Arrays of Objects in Java: A Simple Guide

Using Arrays of Objects in Java: A Simple Guide

Java lets you create and manage multiple objects using arrays. In this guide, we’ll explore how to use arrays of objects to handle student information.

Step 1: Create a Student Class

First, define a Students class with three attributes: name, age, and grade.

class Students {
    String name;
    int age;
    int grade;
}

Step 2: Create Student Objects

Next, create three student objects and assign values to their attributes.

public class Main {
    public static void main(String[] args) {
        Students s1 = new Students();
        s1.name = "John";
        s1.age = 22;
        s1.grade = 99;

        Students s2 = new Students();
        s2.name = "Jane";
        s2.age = 24;
        s2.grade = 98;

        Students s3 = new Students();
        s3.name = "Mary";
        s3.age = 28;
        s3.grade = 94;

Step 3: Store Students in an Array

Store the student objects in an array.

Students[] students = new Students[3];
        students[0] = s1;
        students[1] = s2;
        students[2] = s3;

Step 4: Display Student Information

Use a loop to display each student’s information.

        for (Students student : students) {
            System.out.println("Name: " + student.name + ", Age: " + student.age + ", Grade: " + student.grade);
        }
    }
}

Complete Program

Here’s the full Java program:

package arrayOfObject;

class Students {
    String name;
    int age;
    int grade;
}

public class Main {
    public static void main(String[] args) {
        Students s1 = new Students();
        s1.name = "John";
        s1.age = 22;
        s1.grade = 99;

        Students s2 = new Students();
        s2.name = "Jane";
        s2.age = 24;
        s2.grade = 98;

        Students s3 = new Students();
        s3.name = "Mary";
        s3.age = 28;
        s3.grade = 94;

        Students[] students = new Students[3];
        students[0] = s1;
        students[1] = s2;
        students[2] = s3;

        for (Students student : students) {
            System.out.println("Name: " + student.name + ", Age: " + student.age + ", Grade: " + student.grade);
        }
    }
}

Conclusion

Arrays of objects in Java help you manage multiple items of the same type, like student records. By defining a class and storing instances in an array, you can easily organize and handle related data.

Happy coding!