Skip to main content

Java Instanceof keyword HackerRank Solution with explanation

Java Instanceof keyword with Examples

Java Instanceof keyword with Examples

What is instanceof keyword in java?

instanceof is a binary operator used to test if an object is of a given type. 

In other word, instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.

The result of the operation is either true or false. It's also known as type comparison operator because it compares the instance with type.

Syntax :

object instanceof Object (type)

Problem description :

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.

See full description on HackerRank :

So lets see solution :

import java.util.*;


class Student{}
class Rockstar{}
class Hacker{}


public class InstanceOFTutorial{
    
   static String count(ArrayList mylist){
      int a = 0,b = 0,c = 0;
      for(int i = 0; i < mylist.size(); i++){
         Object element = mylist.get(i);
        
         if (element instanceof Student)
            a++;
         if (element instanceof Rockstar)
            b++;
         if (element instanceof Hacker)
            c++;

     
      }
      String ret = Integer.toString(a)+" "+ Integer.toString(b)+" "+ Integer.toString(c);
      return ret;
   }

   public static void main(String []args){
      ArrayList mylist = new ArrayList();
      Scanner sc = new Scanner(System.in);
      int t = sc.nextInt();
      for(int i=0; i<t; i++){
         String s=sc.next();
         if(s.equals("Student"))mylist.add(new Student());
         if(s.equals("Rockstar"))mylist.add(new Rockstar());
         if(s.equals("Hacker"))mylist.add(new Hacker());
      }
      System.out.println(count(mylist));
   }
}

Solution explanation :

  • We have to check only how many total Student, Rockstar and Hacker instance is in given list.
  • So in if condition we have to check all three condition using instanceof keyword.
  • So using instanceof we get all total number of Student, Rockstar and Hacker instances and increment a, b and c variable value according instances stored in given list.

Why we have to use instanceof keyword in Java?

When we do typecast, it is always a good idea to check if the typecasting is valid or not. 

We must always first check for validity using instancof, then do typecasting.

// Parent class
public class SuperClass {
    int value = 10;
}

// Child class
public class SubClass extends SuperClass {
    
    int value = 20;

    public static void main(String[] args) {
       
        SuperClass obj1 = new SubClass();
       
        SuperClass obj2 = obj1;
       
        System.out.println("Before type-casting : "+ obj2.value);
        if (obj2 instanceof SubClass) {
            System.out.println("After type-casting : "+ ((SubClass)obj2).value);
        }
    }
}

Output :

Before type-casting : 10
After type-casting : 20

What if we create object of SubClass and try to type cast into Child class? so lets see below example.

// Parent class
public class SuperClass {
        int value = 10;

// Child class
public class SubClass extends SuperClass {
    
    int value = 20;

    public static void main(String[] args) {
       
        SuperClass obj1 = new SuperClass();
       
        System.out.println("Before type-casting : "+ obj1.value);

//        if (obj1 instanceof SubClass) {
            System.out.println("After type-casting : "+ ((SubClass)obj1).value);
//        }
    }
}

Output :

Before type-casting : 10
Exception in thread "main" java.lang.ClassCastException:

If we remove commented part, then we does not get ClassCastException.

See other articles :

Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...