Java From Beginner To Advanced

0% completed

Previous
Next
instance of operator

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.

The instanceof Operator

OperatorDescriptionExample
instanceofChecks if an object is an instance of a specified class or interfaceobject instanceof ClassName

Example 1: Using instanceof with Built-in Types

Below is an example that uses the instanceof operator to verify the type of a built-in object.

Java
Java

. . . .

Explanation:

  • The variable obj is declared as an Object but is initialized with a string literal.
  • The instanceof operator confirms that obj is an instance of String, returning true.
  • Since every object in Java is derived from the class 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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next