AppDividend
Latest Code Tutorials

Java instanceof Operator Example | instanceof In Java

0

Java instanceof Operator Example | instanceof In Java is today’s topic. An instanceof is a keyword in Java that has been mainly used for checking whether a variable is containing the given type of object reference or not. The instanceof operator of Java is known as type comparison operator because it compares instance with type.

It can return true or may be false. Suppose we are applying instanceof with any of the variables that contain a null value in it then it will return false. We have already covered the operators in java.

Content Overview

#What is the instanceof Operator

An instanceof is a binary operator used to test if an object is of a given type.

The result of the operation is either true or false. It’s also known as type comparison operator because it compares the instance with type.

Before casting an unknown object, the instanceof check should always be used. Doing this helps in avoiding ClassCastException at runtime.

The instanceof operator’s basic syntax is following.

(object) instanceof (type)

Java instanceof Operator

An instanceof operator is used to testing whether an object is the instance of the specified type (class or subclass or interface).

An instanceof in Java is also known as type comparison operator because it compares an instance with type. It returns either true or false.

If we apply an instanceof operator with any variable that has a null value, it returns false.

Let’s understand the topic through an example.

class Instance {
  public static void main(String arg[]) {
    Instance i = new Instance();
    System.out.println(i instanceof Instance);
  }
}

/**
 * If it contains null value then the example will be:
 */

class Instance {
  public static void main(String arg[]) {
    Instance i = null;
    System.out.println(i instanceof Instance);
  }
}

#Downcasting with Java instanceof operator

When the object of the Parent class is referred to as Subclass type. Then it is called as Downcasting. But if we perform it as it is then our compiler will show us compilation error, and if we perform it through typecasting, then there is ClassCastException will be thrown at runtime.

So the simplest way is downcasting through which it is possible.

See the following code.

Book b = new Stationary();
/** It will show compilation error.
So we have to write **/
Book b=(Book) new Stationary();

Here comes no problem it will compile successfully, but there is an exception thrown that is ClassCastException as we are doing ClassCast in this example.

#Downcasting without Java instanceof operator

See the following code.

class Book extends Stationary {
  static void method(Stationary s) {
    Book b = (Book) s;
    System.out.println("Perform");
  }

  public static void main(String arg[]) {
    Stationary s = new Book();
    Book.method(s);
  }
}

Now you are thinking about the applications of instanceof.

So let’s review what we have learned in these lectures is that parent class data members can be accessed by when the reference of parent type refers to the child object and we can access child members through typecasting.

Syntax: (child_class_name) Parent_Reference_variable).func.name().

When typecasting is performed them, we have to check whether that typecasting is convenient or not and for this instanceof helps the most. We, first of all, check our validity of instanceof function then we can perform our typecasting.

We can understand this topic better through an example rather than the theory portion.

See the following java program.

class Par {
}

class Child extends Par {
}

class Instance {
  public static void main(String[] args) {
    Child obj = new Child();
    if (obj instanceof Child)
      System.out.println("obj is instance of Child");
    else
      System.out.println("obj is NOT instance of Child");
    if (obj instanceof Par)
      System.out.println("obj is instance of Par");
    else
      System.out.println("obj is NOT instance of Parent");
    if (obj instanceof Object)
      System.out.println("obj is instance of Object");
    else
      System.out.println("obj is NOT instance of Object");
  }
}

See the following output.

instanceof Operator Example

#Using instanceof with the Object Type

In Java, every class implicitly inherits from an Object class. Therefore, using the instanceof operator with the Object type will always evaluate to true.

@Test
public void givenWhenTypeIsOfObjectType_thenReturnTrue() {
    Thread thread = new Thread();
    Assert.assertTrue(thread instanceof Object);
}

#Using the instanceof Operator When an Object is null

If we use the instanceof operator on any object that is null, it returns false. Also, no null check is needed when using an instanceof operator.

@Test
public void givenWhenInstanceValueIsNull_thenReturnFalse() {
    Circle circle = null;
    Assert.assertFalse(circle instanceof Round);
}
Finally, instanceof In Java Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.