How to use Instanceof Operator in Java?

 Instanceof Operator in JAVA




Instanceof  Operator determine the type of an object(Class type/ Interface type/Array type).Instanceof Operator verifies whether its first operand is an instance of its second.


Syntax of instanceof
A instanceof B

A must be the name of an object and B  must be the name of a class/interface/array type.

An object is considered to be an instance of a class if the object directly or indirectly descends from that class.

As Example:



class X {
}


class Y extends X{
}

X x = new Y();

if (x instanceof  X) {

   System.out.println("Instance of  X");

}



if (x instanceof  Y) {

   System.out.println("Instance of  Y");

}
In the above Example, the Output  will be Instance of  X
Instance of  Y

Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

1 comments:

  1. When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I
    get three emails with the same comment. Is there any way you
    can remove people from that service? Thank you!


    My website cigarette electronique

    ReplyDelete