Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof Operator!!

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi folks,
i read that the instanceof operator allows us to check if an object is of a particular class. but i am wondering why not us == operator to achieve the same thing? could you please clarify this to me?
thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64843
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For objects, the == operator is used to test for object identity; that is, are the two objects the SAME object.
instanceof tests if an object is an instance of a class.
hth,
bear
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to what Bear said, remember that any parent class or interface that is implemented by the objcet will test true using instanceof. For example:
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code that should be the same if we use your code:

You can see that == does not behave the same as instanceof.
Dave
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bah, that's what you get for getting distracted mid-reply
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic