What is the purpose of the instanceOf keyword in Java?
The instanceof keyword is used to check if an object is an instance of a certain class. It is used to determine if an object is an instance of a class, or of one of its subclasses or implementing classes.
The instanceof keyword can be used to determine the type of an object at runtime and then handle it accordingly. It will return true if the object is an instance of the specified class, a subclass, or an implementing class; otherwise, it will return false.
For example, you can use the instanceof keyword to determine if an object is an instance of a String type.
String str = "Hello";
if (str instanceof String) {
System.out.println("str is an instance of String");
}
The instanceof keyword can also be used to determine if an object implements a certain interface.
List<String> list = new ArrayList<>();
if (list instanceof List) {
System.out.println("list is an instance of List");
}
if (list instanceof Collection) {
System.out.println("list is an instance of Collection");
}
In the code above, list is an instance of ArrayList, as well as an instance of List and Collection, so using the instanceof keyword to check will return true for all of them.