๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

instanceof Operator in Java  


Introduction

  • The instanceof operator is used to check if an object is an instance of a specific class or implements a given interface.
  • It returns a boolean value: true if the object is an instance of the specified class or interface, and false otherwise.
  • It is commonly used for type checking in Java.
  • Syntax:
    object instanceof ClassName
    • object: The reference variable pointing to the object being tested.
    • ClassName: The class or interface that you want to check the type of the object against.
  • Program:
    class Animal 
    {
        // some methods
    }
    
    class Dog extends Animal
    {
        // some methods
    }
    
    public class InstanceOfExample
    {
        public static void main(String[] args)
        {
            Animal animal = new Dog();  // Animal reference, but Dog object
    
            // Using instanceof to check the type
            if (animal instanceof Dog)
            {
                System.out.println("The animal is a Dog");
            }
            else
            {
                System.out.println("The animal is not a Dog");
            }
        }
    }
    Output:
    The animal is a Dog
Some Advance Important Points :-
  • Usage of instanceof Operator:
    • Type Checking: It checks if an object is an instance of a particular class or interface.
      For example :-
      String str = "Hello";
      System.out.println(str instanceof String); // Output: true
    • Interface Type Checking: Checks if an object implements a particular interface.
      For example :-
      List<String> list = new ArrayList<>();
      System.out.println(list instanceof List); // Output: true
  • Null Check:
    • The instanceof operator will always return false when the object being checked is null.
    • String str = null;
      System.out.println(str instanceof String); // Output: false
  • Inheritance with instanceof:
    • Inheritance Hierarchy: The operator works well with inheritance, checking if an object is an instance of a superclass or subclass.
    • class Animal {}
      class Dog extends Animal {}
      
      Animal a = new Dog();
      System.out.println(a instanceof Dog);  // Output: true
      System.out.println(a instanceof Animal);  // Output: true
  • Use in Interfaces:
    • The instanceof operator also works with interfaces. It checks if an object implements a specific interface.
    • interface Playable {}
      class Football implements Playable {}
      
      Playable game = new Football();
      System.out.println(game instanceof Playable);  // Output: true
  • Performance:
    • The instanceof operator is generally fast as it is a runtime check.
    • Inheritance Hierarchy Traversal: It checks the class hierarchy, starting from the actual class and moving up to the Object class. This is efficient but can cause slight overhead in complex hierarchies.
  • instanceof with switch (Java 16+):
    • Starting from Java 16, instanceof can be used in a switch statement with pattern matching.
    • Object obj = new Dog();
      switch (obj) {
          case Dog d -> System.out.println("It's a dog!");
          case Cat c -> System.out.println("It's a cat!");
          default -> System.out.println("Unknown animal");
      }
  • instanceof with Type Casting:
    • The instanceof operator is often used in conjunction with casting to safely cast objects.
    • Object obj = "Hello";
      if (obj instanceof String) {
          String str = (String) obj;  // Safe cast
          System.out.println(str.length()); // Output: 5
      }
  • instanceof with Generics:
    • The instanceof operator can be used with generics, but due to type erasure in Java, it can only check the raw type of the generic class.
    • List list = new ArrayList<>();
      if (list instanceof ArrayList) {
          System.out.println("It's an ArrayList");
      }