instanceof” keyword is used to check what is the type of object. F
The instanceof
keyword in Java is used to test whether an object is an instance of a particular class, interface, or subclass. It is a binary operator that returns a boolean value – true
if the object is an instance of the specified type, and false
otherwise.
Here’s a basic example:
public class Example {
public static void main(String[] args) {
String str = "Hello, World!";
// Using instanceof to check if str is an instance of String classif (str instanceof String) {
System.out.println(“str is an instance of String class”);
} else {
System.out.println(“str is not an instance of String class”);
}
}
}
In this example, instanceof
is used to check if the variable str
is an instance of the String
class. If it is, the first part of the if
statement is executed; otherwise, the else
part is executed.
The instanceof
operator is particularly useful in situations where you need to determine the type of an object before performing certain operations or casting it to a specific type to avoid runtime errors.