instanceof Operator in Java

The instanceof operator is used to check if an object is an instance of the specified class or subclass of that class. If this is the case, instanceof returns the boolean true;otherwise, it returns false.

For example, in the code fragment

Integer intobj = new Integer(7);
if (intobj instanceof Integer)
{
System.out.println("intobj is an Integer");
}
if (intobj instanceof Object)
{
System.out.println("intobj is an Object");
}


since java.lang.Integer is a subclass of java.lang.Object, both if statements are true.

No comments:

Post a Comment