aspose file tools*
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
Author

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?
thanks
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61657
    
  67

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


[Asking smart questions] [Bear's FrontMan] [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
Rancher

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

Joined: Mar 06, 2001
Posts: 13459

Bah, that's what you get for getting distracted mid-reply
 
 
subject: instanceof Operator!!