Explain about instanceof operator in java?

Instanceof operator is used to test the object is of which type.

Syntax :

 <reference expression> instanceof <destination type>

instanceof Instanceof returns true if reference expression is subtype of destination type.

Instanceof returns false if reference expression is null.

Example :

public classInstanceOfExample 
{
public static voidmain(String[] args) 
{
Integer a = newInteger(5);
if (a instanceof java.lang.Integer) { System.out.println(true); } 
else { System.out.println(false); }
}
}

Since a is integer object it returns true.
There will be a compile time check whether reference expression is subtype of destination type.

If it is not a subtype then compile time error will be shown as Incompatible types


Posted

in

Tags:

Comments

Leave a Reply