In Java, the instanceof keyword is used to check whether an object is an instance of a particular class or interface. For example:

Object msg = new String("Hello");
if (msg instanceof String) {
    System.out.println("A String");
}

The instanceof statement returns true if the variable is of type (or subtype) of the specified class. The above code will give the output "A String" because msg is of type String.

So we can consider instanceof as an operator. It is widely used in when overriding the equals() method, for example:

public class Student {
 
    public boolean equals(Object obj) {
        if (obj instanceof Student) {
        	// comparing...
        }
 
        return false;
    }
}

Related keyword: if..else. See all keywords in Java.

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#2Nam2020-09-12 09:39
Hi Abdulateef,
Thanks for your sharp eyes. I've fixed that typos.
Quote
#1Abdulateef Olawale L2020-09-12 08:07
Hi Nam,
nice article..please there is a type error of calss instead of class.

weldon
Quote