The Java instanceof operator Explained with Examples

instanceof operator

The instanceof operator allows you to check the validity of a IS A relationship. If at any point of time, we are not sure about this and we want to validate this at runtime, we can do the following:

//assuming vehicle is an instance of Class `Car` the expression inside the 'if' will  return true
if(vehicle instanceof Car){
    //do something if vehicle is a Car

Note : If you apply the instanceof operator with any variable that has null value, it returns false.

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.


if (obj instanceof Checkbox)
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();

More about…instanceof in java