Student details using an array of objects: Java Exercise

You’ll learn to implement a program for Student details using an array of objects in Java.

EXERCISE: Create an array of objects of the Student class, of size 3. The Student class is defined below. Create three objects of the Student class, with values, and assign the objects to the array. Loop through the array and print the name, grade, and email of all students as below:

Peter 3 [email protected]
John 4 [email protected]
Lisa 5 [email protected]
public class Sample {

	public static void main(String[] args) throws Exception {

		// Create an array of 3 objects of Student class.

		// Store objects

		// loop through the array and display name, grade, and email of students

	}
}
class Student {
	private String name;
	private int grade;
	private String email;

	public Student(String name, int grade, String email) {

		this.name = name;
		this.grade = grade;
		this.email = email;
	}

	public String toString() {

		return name + " " + grade + " " + email;
	}
}

SOLUTION

We’ll create an array of 3 objects for the Student class. Notice that each index corresponds to each object i.e. Peter, John and Lisa created with a new keyword.

In this code example, a student class constructor is used to pass the details of a student at the time you create an object. And toString() method is used to print the object’s information name, grade and email.

Java Code:

public class Sample {

	public static void main(String[] args) {
		Student[] s = new Student[3];// Array of objects.

		s[0] = new Student("Peter", 3, "[email protected]");
		s[1] = new Student("John", 4, "[email protected]");
		s[2] = new Student("Lisa", 5, "[email protected]");

		for (int i = 0; i < 3; ++i) {
			System.out.println(s[i].toString());
		}
	}
}

INTENT: The exercise intends to understand, how to create an array of objects for a user-defined class.

Note that creating an array for user-defined objects is the same as we create an array for in-built data types such as int, float and double, etc. For example,

Here’s an array for 5 int data type: int [] numbers = new int[5];

FOCUS: Make a note, how to create an object of a user-defined class and assign it to an array’s slot. e.g. u[0] = new User(“Peter”, 3, “[email protected]”);

You can also solve this exercise using an ArrayList. You can read the concepts for the ArrayList of Objects in Java.

Related Posts