Java Instanceof Operator And Its Applications

May 09, 2022
Javainstanceofoperatoranditsapplications Xblog1



Introduction

Java instanceof operator, also referred to as type comparison operator, is used to check the type of object passed. It verifies whether the reference variable contains the given type of object reference or not. Java instanceof also checks whether an object reference belongs to the parent class, child class, or an interface.

new java job roles

The instanceof operator returns a Boolean value, either true or false, based on the following basic rules:

The Java instanceof operator will return True if:

  • The passed object is the same as its class type.
  • The passed object is a child object and is the same as its parent object type or the complete object hierarchy is passed up to the Object class.

The Java instanceof operator will return False if:

  • The passed object is checked against the type and is not in its hierarchy.
  • The passed object value is null.
  • The parent object is not the same as the child object type.

Syntax of Java instanceof operator

<object> instanceof <type>

This is the basic syntax of Instanceof operator and the object mentioned here is where an object reference variable is placed. The type can be a class or an interface that has to be checked. It can be assigned to a Boolean variable as it returns true or false or it can be directly printed on the screen. See both examples here:

1. Boolean var;
2. Var = obj01 instanceof class01;

The returned value will be now stored in the variable “var”.

System.out.println(obj01 instanceof class01);

This line of code will simply output the result, true or false on screen.

Applications of Java instanceof operator

Following are some of the prominent applications of instanceof Java operator. It also includes different types of verifications that instanceof operator is known for:

· Checking object reference type:

As discussed, the primary application of Java instanceof is testing the object reference type. The code mentioned below is a simple demonstration to understand the use of Java instanceof operator for checking reference type. Here the reference type of object (obj) is the same as the type of class (typeCheck) so it will return true.

1. public class typeCheck
2. {
3.     public static void main(String[] args)
4.     {
5.         typeCheck obj = new typeCheck();
6.         System.out.println(obj instanceof typeCheck);
7.     }
8. }

· Checking Interface reference type:

Similar to object reference check, an interface can also be checked using the instanceof operator in Java. It will return true if the reference object refers to the same interface type.

See the example below:

1. interface intf{
2.   void callMe();
3.  }
4. class example implements intf {
5.   public void callMe() {
6.     System.out.println(the method is called.");
7.   }
8.   public static void main(String[] args) {   
9.     inft a = new example();
10.    // Refering to the class
11.    System.out.println((a instanceof example));
12.    // Refering to the interface
13.    System.out.println((a instanceof intf));
14.   }
15.  }

Output:

true
true

· Checking for null reference variable

In case, if the reference variable holds null value, then the instanceof will always return false like in this example below,

1. class example {
2.   public static void main(String[] args) {   
3.     example obj = null;
4.     System.out.println(obj instanceof example);  
5.   }
6. }

· Checking inherited classes:

Java instanceof operator is useful for inspecting the child class, and verifies the inheritance of whether the child class is inherited or not.

Let’s take another example to understand the instanceof operator.

We created two child classes and one parent class. Now by creating objects, we will verify that the reference object belongs to which class.

Observe this simple example of code where it determines the inheritance by printing true or false.

1. class ParentClass{}
2. class Child01 extends ParentClass{}
3. class Child02 extends ParentClass{}
4.   public static void main(String[] args)
5.   {
6.       ParentClass p =new ParentClass ();
7.       Child01 c1 = new Child01();
8.       Child02 c2 = new Child02();
9.       System.out.println(p instanceof Child01);
10.      System.out.println(p instanceof Child02);
11. //Both of the above statements will return false 
12. //As the parent class object would never inherit a child class object.
13.      System.out.println(c1 instanceof ParentClass);        
14.      System.out.println(c2 instanceof ParentClass);        
15. //Both of these statements will return true as it is correct inheritance.
16.      p = c1;
17.      System.out.println(p1 instanceof Child01);         
18.      System.out.println(p1 instanceof Child02);         
19. //A child object has been assigned to a parent object so the first statement 
20. //should be true as the object was of child01 but the second statement will be false.
21.   }
22. }

The output of this code will be:

false
false
true
true
true
false

· Checking string data type:

As String is a class in Java, string data can also be verified using the instanceof operator. Although this application might seem not to be very useful in a certain case where you are not sure whether the data type is a string or not, you can first check it using instanceof to prevent any errors.

1. Class example{
2. Public static void main(String·args[]) {
3. String str = "It’s a simple string";
4. Int var = 34;
5. if(str1 instanceof String)
6.   System.out.println("str is an instance of the String class");·
7.   else
8.   System.out.println("str is NOT an instance of the String class");
9. if(var instanceof String)
10.  System.out.println("str is an instance of the String class");·
11.  else
12.  System.out.println("str is NOT an instance of the String class");
13.  }
14. }

Output:

str is an instance of the String class
str is NOT an instance of the String class

· Downcasting in Java

Downcasting is the process of holding an object of a parent class in a child class reference object. It is the opposite of upcasting, in which an object of the child class is assigned to the parent class reference object.

Downcasting can be easily done without using instanceof operator like this,

1. class parentClass { }
2.     class childClass extends parentClass {
3.     static void method(parentClass p) {
4.     childClass c = (childClass) p;
5.     System.out.println("downcasting is completed.");
6.   }
7.  }
8.     public static void main(String arg[]) {
9.     parentClass p = new childClass();
10.    childClass.method(p);
11.  }
12. }

The problem in downcasting like this is that here you will encounter a “ClassCastException” exception due to Class Casting done in line 3.

Java instanceof operator takes care of that and also comes in handy when typecasting. It is recommended to check the validity of typecasting first. Instanceof is used here to check whether the typecasting is valid or not before downcasting.

Now, see this example of downcasting is performed using Java instanceof operator:

class ParentClass{ }
public class ChildClass extends ParentClass
{
    public void method()
    {
        System.out.println("Downcasting performed Successfully");
    }
    public static void show(ParentClass p)
    {
       if(p instanceof ChildClass)
       {
           ChildClass c = (ChildClass) p;
           c.method();
       }
    }
    public static void main(String[] args)
    {
      parentClass p =new childClass();
      childClass.show(p); 
      }
}

Output:

Downcasting performed Successfully

Here, we have created a parent class and extended it with a child class. Until now, the code is functioning the same as the one without using the instanceof operator. Now we have another method where the instanceof operator is used to hold the parent class object (p) with the reference to child class object (c).

If the instanceof operator returns true, only then will you be able to downcast successfully and a message will appear on the screen saying so.

See Also: Here’s How to Fix the “Could Not Find or Load Main Class” Error in Java

Conclusion

Java instanceof is a simple operator that primarily deals with the testing of the data type of object reference. It also includes checking that the instance should be of a specified type of class, subclass, or interface. Inheritance checking and downcasting are other notable applications of instanceof that can prevent exceptions and errors in your code. If used properly, the instanceof operator can be utilized to significantly reduce the occurrences of errors and exceptions in your program.

new Java jobs



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US