top

Search

Java Tutorial

.

UpGrad

Java Tutorial

instanceof in Java

Introduction

The instanceof operator uses a keyword to check for given reference objects in a referred variable. Hence, it is renowned as a comparison operator that performs a comparative operation between the instance and the type. The operation's return value is always displayed in Boolean true or false outcomes.

Java programs have featured the instance operator in several versions of the language, including instanceof Java 8, instanceof Java 17, and so on. It is prevalently similar to an is-a relationship depending on the implementation of an interface or the class inheritance of an object class.

The result upon using instanceof in Java is true if the object consists of an instance of the type. It yields similar outcomes when the object forms an instance of a subclass that originated from the type. The return value is true if the type is an interface and an object implements the interface.

Overview

The return values of applying instanceof operator in Java depend on the characteristics of the object and the type. Using instanceof to a parent object can make the outcome false, but applying it while referring to a child using the parent reference returns the result value as true.

This tutorial portrays a synopsis of the different techniques used in the instance method and the behaviors of instanceof in Java, along with providing an elaborate list of instanceof Java example scenarios.

What is the instanceof Operator in Java?

The instanceof operator in Java helps determine an instance's specific category like class, interface, or subclass. An instanceof operator compares an instance with type, hence it is also called the type comparison operator. When a variable consists of a null value, its return value comes as false on using instanceof in Java.

How Does instanceof Java Operator Work?

It is quite similar to other comparison operators as its return values are also presented as true or false. The instanceof operator works using the foundation of is-a connections. An interface implementation or a class inheritance operation forms the basis of the concept of is-a connections.

Simple Example of Java instanceof

public class upGradTutorials {
    public static void main(String[] args) {
        // Create objects of different classes
        Animal animal = new Animal();
        Dog dog = new Dog();
        Cat cat = new Cat();

        // Check if objects are instances of specific classes
        System.out.println(animal instanceof Animal); // true
        System.out.println(dog instanceof Animal); // true
        System.out.println(cat instanceof Animal); // true
        System.out.println(dog instanceof Dog); // true
        System.out.println(cat instanceof Cat); // true
    }
}

// Base class
class Animal {
}

// Derived classes
class Dog extends Animal {
}

class Cat extends Animal {
}

In this example, we have a base class Animal and two derived classes Dog and Cat. We create objects of these classes and then use the instanceof operator to check if the target object is the instance of a specific class.

We create instances of Animal, Dog, and Cat classes inside the main method. We then use the instanceof operator to check the relationship between objects and classes.

The instanceof operator returns true if the object is an instance of the specified class or any of its subclasses. In the example, the objects dog and cat are instances of both the Animal class and their respective derived classes (Dog and Cat).

instanceof in Java With a Variable That Has null Value

In Java, the instanceof operator can also be used to check if an object is an instance of a specific class, even if the object is null. When null is used with the instanceof operator, it will always return false. This is because null does not refer to any object and, therefore, cannot be an instance of any class.

Here is an example: 

public class upGradTutorials {
    public static void main(String[] args) {
        Animal animal = null;

        System.out.println(animal instanceof Animal); // false
        System.out.println(animal instanceof Dog); // false
        System.out.println(animal instanceof Cat); // false
    }
}

class Animal {
}

class Dog extends Animal {
}

class Cat extends Animal {
}

In this example, the variable animal is assigned null. When we use instanceof to check if animal is an instance of Animal, Dog, or Cat, all the expressions will return false since null is not an instance of any class.

Handling null values appropriately in your code to avoid any NullPointerException errors when working with objects is important.

Downcasting With Java instanceof Operator

In Java, downcasting is the process of casting an object reference of a superclass to its subclass type. The instanceof operator is commonly used with downcasting to ensure type safety before performing the cast.

Here is an example:

class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking");
    }
}

class Cat extends Animal {
    public void meow() {
        System.out.println("Cat is meowing");
    }
}

public class upGradTutorials {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        // Downcasting with instanceof and explicit casting
        if (animal1 instanceof Dog) {
            Dog dog = (Dog) animal1;
            dog.bark();
        }

        if (animal2 instanceof Cat) {
            Cat cat = (Cat) animal2;
            cat.meow();
        }
    }
}

In this example, we have a superclass Animal and two subclasses, the Dog and the Cat. We create instances of Dog and Cat and assign them to variables of type Animal. We can then use the instanceof operator to check if the object is an instance of a specific subclass before downcasting.

Using instanceof, we verify if animal1 is an instance of Dog and animal2 is an instance of Cat. If the conditions are true, we can safely downcast the objects to their respective subclass types (Dog and Cat) and invoke subclass-specific methods (bark() and meow()).

Using instanceof before downcasting helps prevent ClassCastException errors by ensuring that the object is of the expected type before performing the cast.

Downcasting Without the Use of Java instanceof

In Java, downcasting without the instanceof operator can lead to runtime exceptions if the object being cast is not an instance of the target class or interface. However, if we are confident about the object type, we can perform the downcast directly.

Here is an example:


In this example, we have a superclass Animal and a subclass Dog. We create an instance of Dog and assign it to a variable of type Animal. Since we are confident that the object is a Dog, we can directly downcast the animal object to type Dog using parentheses and invoke the bark() method.

However, it's important to exercise caution when performing downcasting without instanceof, as it bypasses type checking at compile-time. If the object being cast is not an instance of the target class, a ClassCastException will occur at runtime. It's generally recommended to use instanceof to perform type checks before downcasting to ensure type safety.

Application of instanceof in Java

The data in a parent class member can be accessed using references from the parent type while referring to the child objects. Typecasting allows access to the child data members, where the validity issue can be resolved through the instanceof string Java operator. Commonly applied methods of Java instanceof meaning to improve work efficiency can be enlisted as follows:

  • Checking the inclusion of an object instance in the given variable

  • Scanning the validity of typecasting

  • Referring to the parent object using a subclass type or downcasting

More Examples of Using the instanceof Operator

Example 1: Parent object is not an instance of Child

class Parent {
}

class Child extends Parent {
}

public class upGradTutorials {
    public static void main(String[] args) {
        Parent parent = new Parent();

        // Check if the parent object is an instance of the child class
        System.out.println(parent instanceof Child); // false
    }
}

In this example, we have a parent class Parent and a child class Child. We create an instance of Parent and assign it to a variable of type Parent. When we use the instanceof operator to check if the parent object is an instance of the Child class, it returns false because it is not an instance of the child class.

Example 2: Parent reference referring to a Child is an instance of a Child

class Parent {
}

class Child extends Parent {
}

public class upGradTutorials {
    public static void main(String[] args) {
        Parent parent = new Child();

        // Check if the parent reference referring to a child is an instance of a child
        System.out.println(parent instanceof Child); // true
    }
}

Like the previous example, we have a parent class Parent and a child class Child. Similarly, We create an instance of Child and assign it to a variable of type Parent. When we use the instanceof operator to check if the parent reference referring to a child object is the instance of the Child class, it returns true because the parent reference refers to a child object.

Applying instanceof Operator with Different Parent-Child References

i) Parent Reference Referring to a Parent is an Instance of Parent Only

class Parent {
}

class Child extends Parent {
}

public class upGradTutorials {
    public static void main(String[] args) {
        Parent parent = new Parent();

        // Check if the parent reference is an instance of Parent and Child
        System.out.println(parent instanceof Parent); // true
        System.out.println(parent instanceof Child); // false
    }
}

In this example, we have a parent class Parent and a child class Child. We create an instance of Parent and assign it to a variable of type Parent. The parent reference is referring to a Parent object. Using the instanceof operator, we check if the parent reference is an instance of the Parent and Child classes. The check for Parent returns true because the parent reference is an instance of the Parent class. However, the check for Child returns false because the parent reference is not an instance of the Child class.

ii) Parent Reference Referring to a Child is an Instance of Parent and Child

class Parent {
}

class Child extends Parent {
}

public class upGradTutorials {
    public static void main(String[] args) {
        Parent parent = new Child();
        Child child = new Child();

        // Check if the parent reference and child reference are instances of Parent and Child
        System.out.println(parent instanceof Parent); // true
        System.out.println(parent instanceof Child); // true
        System.out.println(child instanceof Parent); // true
        System.out.println(child instanceof Child); // true
    }
}

Conclusion

The primary utility of the instanceof comparison operator in Java is in determining the distinct type of an object instance, including class, subclass, and interface as the basic categories. It is quite similar to the other comparison operations as instanceof in Java also returns the values in true or false.

Another name for the instanceof operator is a type comparison operator which can perform downcasting without any possible runtime exceptions. If you want to learn more about Java programming, you can opt for courses offered by upGrad. upGrad presents several online courses that can teach you how to use instanceof in Java and numerous other topics.

FAQs

  1. Why is instance used in Java?

Instance variables in Java can be defined as class property that varies from object to object. It can be created by clearing the variables in the class definition. The functionality of instanceof in JavaScript permits the creation of a copy of the data for every object value. 

  1. What is polymorphism in Java?

The word 'polymorphism' stands for 'multiple forms'. Inheritance of a class in Java allows modifications of the attributes and methods using another class, while polymorphism utilizes these methods to conduct numerous tasks. Polymorphism in Java might occur if several interrelated classes are connected by inheritance. 

  1. What are instance methods?

A process that works with the instances of a class and not the class itself is known as the instance method. An instance method can be defined by simply removing static from the method heading. The variables and methods within the method definition can be referred to by using their names and omitting the dots.

Leave a Reply

Your email address will not be published. Required fields are marked *