What is instanceof keyword in Java?
Java instanceof is a keyword. It is a binary operator used to test if an object (instance) is a subtype of a given Type. It returns either true or false. It returns true if the left side of the expression is an instance of the class name on the right side. The instanceof evaluates to true if an object belongs to a specified class or its super class; else raises compilation error. If we apply the instanceof operator with any variable that has null value, it returns false. It is helpful by which your program can obtain run-time type information about an object. The instanceof keyword also known as type comparison operator because it compares the instance with type.
However, with Object car = new Car();,
In the above case, it returns fale because Car is a supertype of Ford and possibly less "refined".
Also, if try ford instanceof Suzuki even does not even compile! This is because Ford is neither a subtype nor a supertype of Suzuki, and it also does not implement it.
It is important to note that the variable used for ford above is of type Object. This is to show instanceof is a runtime operation and brings us to the use case: to react differently based upon an objects type at runtime.
In some other cases also instanceof keyword is a useful tool when you've got a collection of objects and you're not sure what they are. For example, you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
instanceof keyword and null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value.