instanceof operator

 instanceof operator


The instanceof Operator in Java

The instanceof operator in Java is used to test whether an object is an instance of a specific class or a subclass of that class. It helps to ensure type safety and avoid ClassCastException during runtime by checking the type before performing operations that depend on the specific class.

Basic Syntax

The syntax for using the instanceof operator is:

                                                                  object instanceof ClassName

  • object is the reference to the object being tested.
  • ClassName is the class or interface name.

The instanceof operator returns true if object is an instance of ClassName or its subclass; otherwise, it returns false.

Example

Here's a simple example to illustrate the use of instanceof:

class Animal {
// Some properties and methods
}

class Dog extends Animal {
// Some properties and methods
}

public class InstanceOf {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
Animal ad = new Dog(); // Dog object referenced by Animal type variable

System.out.println(a instanceof Animal); // true
System.out.println(d instanceof Dog); // true
System.out.println(d instanceof Animal); // true
System.out.println(a instanceof Dog); // false
System.out.println(ad instanceof Animal); // true
System.out.println(ad instanceof Dog); // true
}
}

Explanation

  • a instanceof Animal returns true because a is an instance of Animal.
  • d instanceof Dog returns true because d is an instance of Dog.
  • d instanceof Animal returns true because Dog is a subclass of Animal.
  • a instanceof Dog returns false because a is not an instance of Dog.
  • ad instanceof Animal returns true because ad is an instance of Animal (it references a Dog object which is a subclass of Animal).
  • ad instanceof Dog returns true because ad is actually referencing a Dog object.

Comments