Junior
What is the purpose of the instanceof operator?
sobes.tech AI
Answer from AI
The instanceof operator is used to check whether an object is an instance of a specific class or subclass, or if it implements a given interface. It returns true if the object matches the type, which is checkable, otherwise false.
Examples of usage:
// Check if o is an instance of the String class
Object o = "hello";
if (o instanceof String) {
System.out.println("Object is a String");
}
# Check if obj is an instance of the list class
obj = [1, 2, 3]
if isinstance(obj, list): # In Python, isinstance() is used
print("Object is a list")