Junior — Middle
What is the purpose of the instanceof operator in Java and how is it used to determine the type of an object?
sobes.tech AI
Answer from AI
The instanceof operator in Java is used to check whether an object is an instance of a specific class or its subclass.
It returns true if the object belongs to the specified type, and false otherwise.
Example usage:
class Animal {}
class Dog extends Animal {}
Animal animal = new Animal();
Dog dog = new Dog();
System.out.println(animal instanceof Animal); // true
System.out.println(dog instanceof Animal); // true, because Dog inherits from Animal
System.out.println(animal instanceof Dog); // false
This is useful when you need to perform different actions depending on the actual type of the object at runtime.