Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to store the detail of 5 student and display .

Java Code Example — Array Programs

ADVERTISEMENT

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

  1. Define a Student class with fields: roll, name, and methods input() and display().
  2. In the main class, declare an array of Student objects: Student[] s = new Student[5];
  3. Start a loop from 0 to 4.
  4. In each iteration, instantiate a new Student object: s[i] = new Student();
  5. Call s[i].input() to read user data for that student.
  6. 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 to null.
  • 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.
ADVERTISEMENT