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();
lightIdentifier.identify(light1);
lightIdentifier.identify(light2);
lightIdentifier.identify(null);

Output:

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.
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations