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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last