by BehindJava

What is instanceof operator in Java

Home » java » What is instanceof operator in Java

In this tutorial we are going learn about instanceof operator in java.

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

The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.

The instanceof operator in Java is used to check if an object belongs to a particular type or not at runtime. It’s also a built-in keyword in Java programming language and mostly used to avoid ClassCastException in Java.

It is used as a safety-check before casting any object into a certain type. This operator has a form of object instanceof Type and returns true if the object satisfies IS-A relationship with the Type i.e. object is an instance of class Type or object is the instance of a class which extends Type or object is an instance of a class which implements interface Type.

Sample Code Snippet:

class Book{
	
}
public class Example1 {
public static void main(String[] args) {
	Book b = new Book();
	if(b instanceof Book) {
		System.out.println("b is type of book");
	}	
}
}

Output:

b is type of book