Skip to main content

ProwessApps

Learn · Practice · Excel

Create a class Student which store name and roll no. of 10 student. Create a method search which can take any no of argument, and display the name according to the roll no. which is passed in argument.

Java Code Example — Polymorphism Programs

ADVERTISEMENT

Create a class Student which store name and roll no. of 10 student. Create a method search which can take any no of argument, and display the name according to the roll no. which is passed in argument.

Objective

Search for multiple students by passing varying numbers of roll numbers using Varargs.

Algorithm / Approach

  1. Create a Student class with an array of objects.
  2. Define a method search(Student[] s, int... a).
  3. The outer loop iterates through the variable arguments a (the roll numbers we are searching for).
  4. The inner loop scans the Student[] s array to see if any student's roll matches the current search target.
  5. In main, call search(s, 1) to search for one student, and search(s, 1, 2, 3) to search for three students simultaneously.
Student.java
import java.util.*;
class Student {
 int roll;
 String name;
 void input() {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Roll: ");
  roll=Integer.parseInt(s.nextLine());
  System.out.print("Enter Name: ");
  name = s.nextLine();
 }
 void search(Student[] s,int...a) {
  for(int x:a) {
   int flag = 0, i = 0;
   for(i = 0; i< s.length; i++) {
    if(x == s[i].roll){
     flag = 1;
     break;
    }
   }
   if(flag==0) {
    System.out.println(x +"-Not Found");
   }
   else {
    System.out.println(x+"-"+s[i].name);
   }
  }
 }
}
class Main {
 public static void main(String... a)
 {
  Student[] s = new Student[5];
  for(int i =0; i< 5; i++) {
   s[i] =new Student();
   s[i].input();
  }
  s[0].search(s,1);
  s[0].search(s,1,2,3);
 }
}

Expected Output

Enter Roll: 1
Enter Name: Alok
Enter Roll: 2
Enter Name: Amritanshu
Enter Roll: 5
Enter Name: Sumit
Enter Roll: 6
Enter Name: Rimu
Enter Roll: 7
Enter Name: Gunja
1-Alok
1-Alok
2-Amritanshu
3-Not Found

Explanation of the Program

  • This program elegantly combines Object Arrays with Varargs.
  • The search method is highly flexible. Because the second parameter is a vararg (int... a), the caller can request to search for as many or as few students as they want in a single method call.
  • Notice that the vararg is placed as the final parameter in the signature. If it were placed first, the compiler wouldn't know where the integers end and the Student array begins.

Complexity

Time Complexity O(n * m) - Where n is the number of varargs passed and m is the number of students in the array.
Space Complexity O(n) - For the vararg array allocation.
ADVERTISEMENT