instanceof Java Keyword

instanceof Java Keyword

Introduction

The instanceof keyword is very useful to know whether an object belongs to which class. The instanceof evaluates to true if an object belongs to a specified class or its super class; else raises compilation error. The following program illustrates.


instanceof Java Keyword
Output screenshot of instanceof Java Keyword

The objects s1, d1 and id are checked whether they belong to String, a Double or InstanceDemo class.

The instanceof keyword evaluates to true even when the object is checked with its super class.


instanceof Java Keyword
Output screenshot of instanceof Java Keyword

scc is an object of SuperClassCheck. The scc object is checked with the classes SuperClassCheck, Hello and Test. All are evaluated to true as Hello and Test are super classes.

if(scc instanceof Object)

The above statement also evaluates to true as Object class is implicit super class of all Java objects.

Think that you know there is an object that belongs to some wrapper class. You can find out for which wrapper class the object belongs. The following program illustrates.


instanceof Java Keyword
Output screenshot of instanceof Java Keyword

Double d1 = new Double(20.6);
Object obj = d1;

Here, a small programming technique is implemened. The Double object d1 is assigned to obj of Object class. Now, obj contains the reference of Double. The Double object d1 is checked with every wrapper class.

instanceOf

There does not exist an instanceof method in Java language as such. This search term by the novice can be interpreted as "instanceof used in a method"; the method finds out to which class the object passed as parameter belongs. In the following code, an Object class parameter is passed to the method findOut() and in the body checked for which class this object belongs.

To the findOut() method two objects are passed, at different times, and found out for which class Test or Hello, the objects t1 and h1 belongs. As per the instanceof keyword evaluation, the variables x or y are called and printed.

instanceOf Interface

In the above program, the Test and Hello can be interfaces and still the program executes smoothly.

Between two interfaces, extends keyword should be used.

7 thoughts on “instanceof Java Keyword

  1. Abhinay

    Hello Sir,

    In the instanceOf method example we have Hello, Test and Demo as 3 different classes. We did not inherit Demo from either Hello or Test, then how it is possible to create the objects inside the Demo class.

    Plz explain.

  2. Swish22 Coupon Code

    I blog frequently and I seriously appreciate your information.
    This article has really peaked my interest.
    I will bookmark your website and keep checking for new details about once a week.
    I subscribed to your Feed too.

Leave a Reply

Your email address will not be published. Required fields are marked *