instanceof Operator in Java:
The instanceof operator is used to check whether an object is an instance of a specific class or subclass. It returns a boolean value — true if the object is of the specified type, otherwise false.
Syntax
object instanceof ClassName
Use Case
Useful when working with inheritance, polymorphism, or type checking before casting an object.
Example:
public class ShikshaSanchar {
public static void main(String[] args) {
String name = "Simran";
Integer number = 100;
System.out.println(name instanceof String); // true
System.out.println(number instanceof Integer); // true
System.out.println(name instanceof Object); // true
Object obj = "Hello";
System.out.println(obj instanceof String); // true
System.out.println(obj instanceof Integer); // false
}
}
Output:
true
true
true
true
false
Explanation:
- name instanceof String → true, because name is a String.
- number instanceof Integer → true, since number is an Integer.
- name instanceof Object → true, because all classes in Java inherit from Object.
- obj instanceof String → true, as obj refers to a String.
- obj instanceof Integer → false, obj is not an Integer.
Example: null Check
public class ShikshaSanchar {
public static void main(String[] args) {
String str = null;
System.out.println("Is str an instance of String? " + (str instanceof String));
}
}
Output:
Is str an instance of String? false
Explanation:
- str is declared as a String but currently holds null.
- instanceof checks whether str refers to a valid object of type String.
- Since null doesn’t point to any object, str instanceof String → false.
Summary:
- instanceof checks if an object belongs to a class or subclass.
- Returns true if object is compatible with the class type.
- Useful in type checking and avoiding ClassCastException.
- Works with interfaces too: obj instanceof InterfaceName.
- null instanceof Type always returns false, because null doesn't refer to any actual object in memory.