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 began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on 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