0% completed
The instanceof operator in Java is used to test whether an object is an instance of a specified class or interface. It returns a boolean value (true or false) based on the comparison. This operator is particularly helpful when you work with class hierarchies or need to verify an object's type before performing type-specific operations.
| Operator | Description | Example |
|---|---|---|
instanceof | Checks if an object is an instance of a specified class or interface | object instanceof ClassName |
Below is an example that uses the instanceof operator to verify the type of a built-in object.
Explanation:
obj is declared as an Object but is initialized with a string literal.instanceof operator confirms that obj is an instance of String, returning true.Object, the operator also confirms that obj is an instance of Object, returning true.The instanceof operator is a powerful tool in Java for ensuring type safety and performing type-specific logic. It is especially useful in scenarios involving polymorphism and class hierarchies.
.....
.....
.....