What is instanceof operator?
It is used to check if an object is belongs to a particular type such as class, subclass or interface at runtime.
It is comparator operator and return true or false. If value is null it returns false.
It is a predefined keyword and compares the instance with type.
It is mainly used to avoid ClassCastException in Java.
Program of instanceof operator:-
class Test
{
public static void main(String args[])
{
Test obj=new Test();
System.out.println(obj instanceof Test);
}
}
OutPut:-
true
Program of handle exception with instanceof operator:-
class Four
{
public static void main(String args[])
{
try
{
int n=Integer.parseInt(args[0]);
int m=Integer.parseInt(args[1]);
System.out.println(n/m);
Thread.sleep(5000);
}
catch(Exception e)
{
if(e instanceof ArrayIndexOutOfBoundsException)
{
System.out.println("aioobe");
}
else if(e instanceof ArithmeticException)
{
System.out.println("arithmetic");
}
else if(e instanceof NumberFormatException)
{
System.out.println("n f");
}
else if(e instanceof InterruptedException)
{
System.out.println("intr");
}
}
System.out.println("Radhey Krishna");
}
}
OutPut:-
aioobe
Radhey Krishna