print
Advertisment
Advertisment

instanceof operators in java

Instanceof is a binary operator that Which is used to check the reference type of the object checks whether an object is an instanceof a given type. We can use instanceof operator to check whether an object reference belongs to parent class, child class, or an interface.It's known as a type comparison operator because it compares the instance with type. Before casting an unknown object, the instanceof check should always be used.

Example

		
	class Objectref{
		public void method(){
			System.out.println("object refrence");
		}
	}
	class CheckIfInstance{
		public static void main(String[] args) {
			Objectref o = new Objectref();
			o.method();
			System.out.println(o instanceof Objectref);
		}
	}
		
	

Output :

	
	
		object refrence
		true
	

Advertisment

use of downcasting in the instanceof operator

We can perform downcasting in Java by using instanceof operator. When the subclass type refers to the parent class of an object, it is called downcasting. When we perform downcasting directly, it gives compilation error. And when we perform it by typecasting then it gives ClassCastException at runtime. But when we use instanceof then it is possible to do it.

Advertisment
Advertisment
arrow_upward