Why is it, that if I need to check equality between two strings I have to use String.equals() rather than ==?
Printable View
Why is it, that if I need to check equality between two strings I have to use String.equals() rather than ==?
This is because strings are objects. An object is an instance of a class, in other words your String variable is a reference to a String object. If you use the == operator you are comparing the reference value rather than the object itself.
I thought equals was one of those special methods link toString() which is invoked when two objects are compared?
Java does not support operator overloading, so AFAIK the == operators will always compare object instances, whereas a specific .equals method can do what it likes (in this case compare string content). In .NET it is the other way round, the string class overloads the == operator for string comparison and .Equals executes a reference comparison.
Which, IMHO, is quite braindead of C#. (Read: unintuitive) But I'm sure some people will disagree.
== always compares the variable values in Java, no exceptions. And since every variable but the primitives is of reference type, it's always the reference value that's compared for objects.
Thanks for the help. I just assumed that it be like the toString() method because all objects have an equals method. Out of interest would a comparison here be that of primitive types?
Or would that again be a comparison between two references to String objects?Code:if ("String1" == "String2")
String literals in Java are String objects, so the latter I'd assume.
It would be objects. On the other hand, string literals are, I believe, interned, so identical string literals are actually the same object. At least in Sun's JVM.
Also, toString() isn't as magical as you think. You may think that a string concatenation automatically generates toString() calls, but it really doesn't. This:
is translated to this (JDK 1.5):Code:"The current date and time is " + new Date() + "."
The "magic" of this comes from the overloaded append() method, which has the obvious String one and one for Object, that works like so:Code:new StringBuilder().append("The current date and time is ").append(new Date()).append(".")
Other overloads are provided for the primitives.Code:public StringBuilder append(Object o) {
return append(o.toString());
}