Java instanceof Keyword — Java Technical Interview Questions & Answers
Java instanceof Keyword
Java instanceof Keyword
- instanceof checks: is this object an example of that type? Expression: obj instanceof Type → true or false. Use it before a cast so you avoid ClassCastException.
- It understands inheritance: Dog instanceof Animal can be true. null instanceof Anything is always false — a favourite MCQ.
- Show Animal a = new Dog(); then a instanceof Dog and a instanceof Animal. Don’t cast blindly in uncertain hierarchies.
- Let's take this on the board with one tiny Main class — no extra files. Java instanceof Keyword — output: true then true. d is a Dog, and because Dog extends Animal, d instanceof Animal is also true. Start from main, go line by line, and stop at each print. That output is the proof for instanceof Keyword.
Technical Interview Tip: null instanceof X is false — common MCQ.
Code Examples for Java instanceof Keyword
Example
class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a instanceof Dog);
System.out.println(a instanceof Animal);
}
}Java instanceof Keyword — output: true then true. d is a Dog, and because Dog extends Animal, d instanceof Animal is also true.
How to Explain Java instanceof Keyword to an Interviewer
What does instanceof return?
true or false
Why use instanceof before cast?
Avoid ClassCastException
What is null instanceof String?
false