Menu
Coddy logo textTech

The instanceof Operator

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 31 of 87.

The previous lesson showed that downcasting can fail with a ClassCastException if the object isn't actually the type you're casting to. The instanceof operator solves this by letting you check an object's type before casting.

The syntax is straightforward: object instanceof ClassName returns true if the object is an instance of that class (or any of its subclasses):

Animal animal = new Dog();

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
    dog.bark();  // Safe to call Dog-specific methods
}

This check prevents runtime errors by ensuring the cast will succeed. The operator also returns true for parent types in the hierarchy:

Dog dog = new Dog();
System.out.println(dog instanceof Dog);     // true
System.out.println(dog instanceof Animal);  // true
System.out.println(dog instanceof Object);  // true

Since Java 16, you can combine the check and cast in one step using pattern matching:

if (animal instanceof Dog dog) {
    dog.bark();  // 'dog' is already cast and ready to use
}

This cleaner syntax eliminates the separate cast line. Note that instanceof returns false when tested against null, so you don't need a separate null check.

challenge icon

Challenge

Easy

Let's build a vehicle inspection system that uses the instanceof operator to safely identify and handle different vehicle types. You'll create a hierarchy of vehicles and write code that checks each vehicle's actual type before accessing its specialized features.

You'll organize your code across four files:

  • Vehicle.java: Create the base class that all vehicles share. Every vehicle has a model field (String). Include a constructor to initialize it, a getter method getModel(), and a method inspect() that prints: Inspecting vehicle: [model]
  • Car.java: Create a class that extends Vehicle. Cars have an additional numDoors field (int). Use super for the parent initialization. Add a method checkDoors() that prints: [model] has [numDoors] doors
  • Motorcycle.java: Create another class that extends Vehicle. Motorcycles have a hasSidecar field (boolean). Add a method checkSidecar() that prints either [model] has a sidecar or [model] has no sidecar depending on the boolean value.
  • Main.java: Here's where instanceof becomes essential! You'll receive four inputs: a car model, number of doors, a motorcycle model, and whether it has a sidecar (true/false).

    Create an array of Vehicle references containing a Car and a Motorcycle. Then loop through the array and for each vehicle:

    • Call the base inspect() method
    • Use instanceof to check if it's a Car - if so, safely downcast and call checkDoors()
    • Use instanceof to check if it's a Motorcycle - if so, safely downcast and call checkSidecar()

You will receive four inputs: the car model (String), number of doors (int), motorcycle model (String), and has sidecar (boolean).

Your output should show four lines - for each vehicle, you'll see its inspection message followed by its type-specific check. The instanceof operator ensures you only call Car methods on actual Cars and Motorcycle methods on actual Motorcycles, preventing any ClassCastException!

Cheat sheet

The instanceof operator checks if an object is an instance of a specific class before casting:

Animal animal = new Dog();

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
    dog.bark();  // Safe to call Dog-specific methods
}

The operator returns true for the object's class and all parent classes in the hierarchy:

Dog dog = new Dog();
System.out.println(dog instanceof Dog);     // true
System.out.println(dog instanceof Animal);  // true
System.out.println(dog instanceof Object);  // true

Since Java 16, pattern matching combines the check and cast in one step:

if (animal instanceof Dog dog) {
    dog.bark();  // 'dog' is already cast and ready to use
}

The instanceof operator returns false when tested against null, eliminating the need for separate null checks.

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs
        String carModel = scanner.nextLine();
        int numDoors = Integer.parseInt(scanner.nextLine());
        String motorcycleModel = scanner.nextLine();
        boolean hasSidecar = Boolean.parseBoolean(scanner.nextLine());
        
        // TODO: Create a Car object with carModel and numDoors
        
        // TODO: Create a Motorcycle object with motorcycleModel and hasSidecar
        
        // TODO: Create an array of Vehicle references containing the Car and Motorcycle
        
        // TODO: Loop through the array and for each vehicle:
        // 1. Call the inspect() method
        // 2. Use instanceof to check if it's a Car, then downcast and call checkDoors()
        // 3. Use instanceof to check if it's a Motorcycle, then downcast and call checkSidecar()
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming