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
Joined: Jan 28, 2005
Refering to my query on equality -
So each time i invoke b1.toString(), does it create a new String object in memory?
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 ]