How the Java instanceof operator works
You can use the Java operator instanceof
to check if an object belongs to a specific class. The operator provides the answer in the form of a Boolean statement, i.e. “true” or “false”. Checking whether the object and class match beforehand can help you to avoid error messages later on.
What is instanceof
in Java?
The nature of some variables in Java is not always immediately apparent. In large Java projects with numerous variables, input data, for example, can cause a variable to appear as different objects. This is why the programming language provides users with instanceof
. This Java operator ensures that the instance of a reference variable really corresponds to a class, subclass or interface. If there’s a match, the operator outputs the Boolean value “true”. If there’s no match, the output is “false”.
When converting an unknown object, it’s important to use Java instanceof
to ensure that the object belongs to the assumed class. If you skip this security check, a ClassCastException could be issued. This occurs when an object needs to be converted into another class. The error message can be confusing and can cause problems if the code is particularly long. That’s why it’s best to use Java instanceof
early on as a safeguard.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
What is the syntax for instanceof
?
When you use instanceof
in Java, the operator compares a reference variable with a specific class that is also specified by the user. It doesn’t include any additional information about the nature of the object or the class. It simply determines whether there is a match or not. The syntax is simple and looks like this:
(object) instanceof (class)
javaIf (object)
is an instance of (class)
, “true” is displayed. If this is not the case, “false” is displayed.
Examples of instanceof
operator in Java
First, we’ll show you a short example to demonstrate how instanceof
works in Java. Here, we’ll create a class called “Animal”.
public class Animal {
}
javaThe next step is to extend this class with a subclass called “Cat”.
public class Cat extends Animal {
}
javaNow we can use Java instanceof
to check whether an instance of Cat belongs to the Animal class. To do this, we’ll use write some more lines of code and output the result with Java command System.out.println
:
public class Animal {}
public class Cat extends Animal {
public static void main(String args []{
Cat cat = new Cat();
System.out.println(cat instanceof Animal);
}
}
javaThe output should look like this:
true
javaMultiple levels and the Object class
This principle also works with the Main class and other subclasses. The next example contains several levels and we’ve extended the instanceof
operator in Java with if-else
. You may notice some additional text placed after two slashes (//). These are Java comments. They explain the individual steps but don’t influence the output.
// Class 1
// Superclass
public class Animal {
}
// Class 2
// Subclass
class Cat extends Animal {
}
// Class 3
// Main class
class Main {
public static void main(String[] args)
Cat cat1 = new Cat();
if (cat1 instanceof Cat)
System.out.println ("cat1 is an instance of Cat");
else
System.out.println ("cat1 is NOT an instance of Cat");
if (cat1 instanceof Animal)
System.out.println ("cat1 is an instance of Animal");
else
System.out.println ("cat1 is NOT an instance of Animal");
if (cat1 instanceof Object)
System.out.println ("cat1 is an instance of Object");
else
System.out.println ("cat1 is NOT an instance of Object");
}
}
javaLooking at our example, we can see that cat1 is an instance of the Cat class and the Animal superclass. As such, the answer to both queries is “true”. Since Object, or the class java.lang.Object
, is at the top of the hierarchy, cat1 is also an instance of Object. So, the Java instanceof
operator will always output true when used with the Object class. The output looks like this:
cat1 is an instance of Cat
cat1 is an instance of Animal
cat1 is an instance of Object
javaOutput with a null value
If a variable has a null value (i.e., does not contain an object), the Java operator instanceof
automatically outputs “false”. Let’s take a look at how this works with the following example:
class Cat {
}
class Main {
public static void main(String[] args)
{
Cat cat2 = null;
if (cat2 instanceof Cat)
System.out.println ("cat2 is an instance of Cat");
else
System.out.println ("cat2 is NOT an instance of Cat");
}
}
javaThe output in this case is:
cat2 is NOT an instance of Cat
javaSuperclass/subclass
Although objects in subclasses also belong to the subclass’s corresponding superclasses, it doesn’t work the other way around. The following example helps to illustrate this aspect of class hierarchy:
class Animal {
}
class Cat extends Animal {
}
class Main {
public static void main(String[] args)
{
Animal bello = new Animal ();
if (bello instanceof Cat)
System.out.println ("Bello is an instance of Cat");
else
System.out.println ("Bello is NOT an instance of Cat");
}
}
javaThe output in this case is:
Bello is NOT an instance of Cat
javaError message for incompatible types
If there is no connection between an object and a class, an error report will be displayed. To illustrate this, let’s create a new class called “Dog” which belongs to the Animal superclass but has no connection to Cat.
class Dog extends Animal {
}
class Main {
public static void main(String[] args)
{
Cat cat3 = new Cat ();
System.out.println (cat3 instanceof Dog);
}
}
javaIn this situation, we’ll receive an error message telling us that there is no connection between the Cat and Dog classes. The message looks like this:
java.lang.Error: Unresolved compilation problem:
Incompatible conditional operand types Cat and Dog
javaIn our Digital Guide, you’ll find more exciting tutorials and informative articles on Java. You can find a comparison of Java and JavaScript as well as one for Java and Python. You can also find out more about Java bitwise operators.