Java

Java instanceof With Examples

In Java, the keyword instanceof is an operator. It determines if the provided object is an instance of the class or interface supplied. Returning either true or false.

To see how instanceof functions, let’s look at a straightforward example:

public class JavaExample {
  public static void main(String[] args) {
    //the obj is an object of "JavaExample" class
    JavaExample obj = new JavaExample();
    System.out.println(obj instanceof JavaExample);
  }
}

Output:

true

Because obj is an object of the given class, it returned true.

How instanceof works?

  • It checks the type indicated by the class name or interface name with the left operand (the object) and returns true if the type matches; otherwise, it returns false.
  • When I say type of class, I mean that it will still return true if you use instanceof to compare an object from a subclass to one from a superclass.

Example 1: Using instanceof with strings

public class JavaExample {
  public static void main(String[] args) {
    String str = "Java is so cool";
    System.out.println(str instanceof java.lang.String);
  }
}

Output:

true

Example 2: Using instanceof with null

An object will always return false if it contains null.

public class JavaExample {
  public static void main(String[] args) {
    JavaExample obj = null;
    System.out.println(obj instanceof JavaExample);
  }
}

Output:

false

Example 3: subclass and superclass

We have a superclass and a subclass in this case. The instanceof operator returned true when we compared the object of the subclass with the object of the superclass.

class MyClass{
}
public class JavaExample extends MyClass{
  public static void main(String[] args) {
    JavaExample obj = new JavaExample();
    //checking subclass object for superclass type
    System.out.println(obj instanceof MyClass);
  }
}

Output:

true

Example 4: instanceof with interface

interface MyInterface{
}
public class JavaExample implements MyInterface{
  public static void main(String[] args) {
    JavaExample obj = new JavaExample();
    //comparing subclass object with parent interface
    System.out.println(obj instanceof MyInterface);
  }
}

Output:

true

Related Articles

Leave a Reply

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

Back to top button