Chapter 6 - Java for Beginners Course

Type Comparison

In this section we’ll be using a slightly modified version of the BluetoothLight and WiFiLight classes from the interfaces section in chapter 5.

In chapter 5 we saw that we can assign an object of one type to an object reference of a superclass, for example:

Light light1 = new BluetoothLight();

We know this is valid as the compiler knows that a BluetoothLight object is a type of Light.

However, if we then try to do this:

BluetoothLight bluetoothLight = light1;

The Java compiler will indicate that it cannot convert from Light to BluetoothLight as in this case we’re going in the opposite direction in our type hierarchy. The compiler knows that light1 is a type of Light but it doesn’t know which.

There will be cases though where given an object we need to make a decision based on its type and ask the compiler to "transform" that object into a different type (either a superclass or subclass of it).

instanceof operator

The instanceof operator allows us to perform type comparisons to establish whether an object is of a given type or not.

Its expression syntax is:

objectref instanceof Type

and it returns a boolean that indicates if the object that objectref is pointing to is of the given Type.

Let’s look at an example:

We’ll be coding a LightIdentifier that will print out the type of Light that has been passed into it:

public class LightIdentifier {
    public void identify(Light light) {
        if (light instanceof BluetoothLight) {
            System.out.println("This is a bluetooth light");
        } else if (light instanceof WiFiLight) {
            System.out.println("This is a wifi light");
        } else {
            System.out.println("Not a bluetooth nor a wifi light");

In this method, we’re using the instanceof operator in conditional statements to decide what to print out based on the type of object.

Let’s give this a try:

In the example code run the JavaTypeComparisonApp
Light light1 = new BluetoothLight();
Light light2 = new WiFiLight();

LightIdentifier lightIdentifier = new LightIdentifier();


This is a bluetooth light
This is a wifi light
Not a bluetooth nor a wifi light

The example above shows that the result of the comparison is decided based on the type of the object and not on the type of the reference.

null will always return false when used in the instanceof operator.