HackerRank Java- Instanceof keyword

The Java instanceof operator is used to test if the object or instance is an instanceof the specified type.

In this problem we have given you three classes in the editor:

Student class
Rockstar class
Hacker class
In the main method, we populated an ArrayList with several instances of these classes. count method calculates how many instances of each type is present in the ArrayList. The code prints three integers, the number of instance of Student class, the number of instance of Rockstar class, the number of instance of Hacker class.

But some lines of the code are missing, and you have to fix it by modifying only 3 lines! Don't add, delete or modify any extra line.

To restore the original code in the editor, click on the top left icon in the editor and create a new buffer.

  1. import java.util.*;
  2. class Student{}
  3. class Rockstar{ }
  4. class Hacker{}
  5. public class InstanceOFTutorial{
  6. static String count(ArrayList mylist){
  7. int a = 0,b = 0,c = 0;
  8. for(int i = 0; i < mylist.size(); i++){
  9. Object element=mylist.get(i);
  10. if(element instanceof Student)
  11. a++;
  12. if(element instanceof Rockstar)
  13. b++;
  14. if(element instanceof Hacker)
  15. c++;
  16. }
  17. String ret = Integer.toString(a)+" "+ Integer.toString(b)+" "+ Integer.toString(c);
  18. return ret;
  19. }
  20. public static void main(String []args){
  21. ArrayList mylist = new ArrayList();
  22. Scanner sc = new Scanner(System.in);
  23. int t = sc.nextInt();
  24. for(int i=0; i<t; i++){
  25. String s=sc.next();
  26. if(s.equals("Student"))mylist.add(new Student());
  27. if(s.equals("Rockstar"))mylist.add(new Rockstar());
  28. if(s.equals("Hacker"))mylist.add(new Hacker());
  29. }
  30. System.out.println(count(mylist));
  31. }
  32. }


Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube