wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Checking equality of objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Checking equality of objects" Watch "Checking equality of objects" New topic
Author

Checking equality of objects

Tresa Antony
Greenhorn

Joined: Jan 28, 2005
Posts: 5
Hi,

Could you please tell me why this equality check results in 'false' ?


Ta much
Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
Hi, it's a little tricky. Strings are not primitives-- they're objects. Primitives compare as you'd expect with ==, but with objects, == compares addresses in memory, so unless you're comparing an object with itself, it won't be equal.

For objects comparision, there are two parts-- first, make sure that it is not null, and then call the equals() method on it. So, something like



Hope This Helps,
jdmaddison
Tresa Antony
Greenhorn

Joined: Jan 28, 2005
Posts: 5
Refering to my query on equality -

So each time i invoke b1.toString(), does it create a new String object in memory?
Qunfeng Wang
Ranch Hand

Joined: Jan 28, 2005
Posts: 430
Yeah.
I think so.


To be or not to be. It's a question.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Tresa Antony:
So each time i invoke b1.toString(), does it create a new String object in memory?
It depends on the class's implementation of toString(). Typically, the answer is yes (for example with Byte and Integer, etc), but some classes either already have a String they can return -- say an Employee class that returns the employee's first name-- or store the built String to be returned for future calls. This latter case is used when building the String representation is very expensive and performance is critical, but it's pretty rare.

In these two cases multiple calls to toString() return the same String, but I cannot stress enough that you should not depend on this behavior since the implementation can be changed or the class could be subclassed, both without you ever knowing. Use the equals() method and you'll never have to worry about it. There's also equalsIgnoreCase() if you need case-insensitive comparisons.

Another good example is String's toString():
[ January 28, 2005: Message edited by: David Harkness ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Checking equality of objects
 
Similar Threads
* Byte == comparision
Please explain this output
related to "=="
toString( ) method
Why is " == " on different strings with same content is returning "false"