Java instanceof keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 12 September 2020   |   Print Email
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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
Thanks for your sharp eyes. I've fixed that typos.
nice article..please there is a type error of calss instead of class.
weldon