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.