
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java instanceof and Its Applications
instanceof operator is used to check the type of object passed. Following rules explain the usage of instanceof operator in Java.
instanceof operator returns true for the object if checked against its class type.
instanceof operator returns false for the object if checked against its type which is not in its hierarchy.
instanceof operator returns true for the child object if checked against parent object type.
instanceof operator returns true for the complete object hierarchy up to the Object class.
instanceof operator returns false for the null value.
instanceof operator returns false for the parent object if checked against child object type.
Following example showcases the above concepts.
Example
class SuperClass { int value = 10; } class SubClass extends SuperClass { int value = 12; } public class Tester{ public static void main(String[] args){ SuperClass obj = new SubClass(); //instanceof returns true for the complete Object Hierarchy if(obj instanceof SubClass){ System.out.println("obj is instanceof SubClass"); } if(obj instanceof SuperClass){ System.out.println("obj is instanceof SuperClass"); } if(obj instanceof Object){ System.out.println("obj is instanceof Object"); } SuperClass obj1 = null; //instanceof returns false for null if(obj1 instanceof SuperClass){ System.out.println("null is instanceof SuperClass"); } SuperClass obj2 = new SuperClass(); //instanceof returns false for the subclass if(obj2 instanceof SubClass){ System.out.println("obj2 is instanceof SubClass"); } if(obj2 instanceof SuperClass){ System.out.println("obj2 is instanceof SuperClass"); } } }
Output
obj is instanceof SubClass obj is instanceof SuperClass obj is instanceof Object obj2 is instanceof SuperClass
Advertisements