Java Program to store the detail of 5 student and display .
Objective
Write a Java program to store the details of 5 students using an Array of Objects.
Algorithm / Approach
- Define a
Studentclass with fields:roll,name, and methodsinput()anddisplay(). - In the
mainclass, declare an array of Student objects:Student[] s = new Student[5]; - Start a loop from 0 to 4.
- In each iteration, instantiate a new Student object:
s[i] = new Student(); - Call
s[i].input()to read user data for that student. - Start a second loop to call
s[i].display()for all 5 objects.
Student.java
import java.util.Scanner;
class Student {
int roll;
String name;
Scanner s=new Scanner(System.in);
public void input() {
System.out.print("Enter Roll: ");
roll=Integer.parseInt(s.nextLine());
System.out.print("Enter Name: ");
name = s.nextLine();
}
public void display() {
System.out.println("Name- "+name);
System.out.println("Roll- "+roll);
}
}
class Main {
public static void main(String[] a)
{
Student[] s = new Student[5];
for(int i=0; i< s.length; i++) {
s[i] =new Student();
s[i].input();
}
for(int i=0; i< s.length; i++) {
s[i].display();
}
}
}
Expected Output
Enter Roll: 12 Enter Name: Alok Enter Roll: 13 Enter Name: Sumit Enter Roll: 14 Enter Name: Ayan Enter Roll: 15 Enter Name: Amritanshu Enter Roll: 16 Enter Name: Rimu Name- Alok Roll- 12 Name- Sumit Roll- 13 Name- Ayan Roll- 14 Name- Amritanshu Roll- 15 Name- Rimu Roll- 16
Explanation of the Program
- Arrays in Java are not limited to primitive data types; you can create arrays of custom objects.
- When you declare
Student[] s = new Student[5];, you are creating an array of 5 *references*, all initially set tonull. - You must instantiate each individual object inside the array using the
new Student()keyword before you can call methods on them, otherwise you will encounter a NullPointerException.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)
Common Mistakes
- Forgetting to instantiate the individual objects in the array (
s[i] = new Student();) before trying to access them.