File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes instanceof Operator!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof Operator!!" Watch "instanceof Operator!!" New topic

instanceof Operator!!

Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
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?
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63844

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.

[Asking smart questions] [About Bear] [Books by Bear]
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
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:

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

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.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Bah, that's what you get for getting distracted mid-reply
I agree. Here's the link:
subject: instanceof Operator!!
jQuery in Action, 3rd edition