Re: String comparison using equals() and ==
Christian wrote:
Chanchal schrieb:
Hello All,
Forgive my ignorance.
I always thought that we should not use == for comparing two different
String objects because == will compare the references and will never
return true even when the value of the compared Strings are the same
Today a colleague of mine showed that I was wrong. Was I always wrong
or recent versions of java included this feature?
Regards
Chanchal
The more recent the Java version is the better the Compiler becomes in
automatically interning Strings. So actually it will very often happen
that == will return true if both Strings were not somehow read over IO
or sth else...
wrapping new String(); around some given string alone won't guarantee
to generate a new String for example but actually a reference to the
same string
I beg to differ. Can you provide reference and/or SSCCE to demonstrate
this flagrant disregard for the JLS.
so
String a = "hello";
String b = "hello";
String b2 = new String("hello");
String b3 = new String(a);
String b4 = (Math.random() < 1.0f? "h":"")+"ello";
a == b will definately be true
though a == b2 should also be true
I doubt that strongly.
so is a == b3
Again, I doubt it.
amazingly a == b4 also returned true here in a test
Hmm, don't think so.
<sscce>
public class Strings {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String b2 = new String("hello");
String b3 = new String(a);
String b4 = (Math.random() < 1.0f ? "h" : "") + "ello";
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("b2 = " + b2);
System.out.println("b3 = " + b3);
System.out.println("b4 = " + b4);
System.out.println("a==b = " + (a==b));
System.out.println("a==b2 = " + (a==b2));
System.out.println("a==b3 = " + (a==b3));
System.out.println("a==b4 = " + (a==b4));
}
}
</sscce>
<output>
a = hello
b = hello
b2 = hello
b3 = hello
b4 = hello
a==b = true
a==b2 = false
a==b3 = false
a==b4 = false
</output>
So my recommendation is use equals for String comparison but be aware
that many more string objects might be the same and comparable with ==
which should mean for you: never use Strings as Monitor for synchronization.
Unless you explicitly intern them.
Even so, there are often better approaches.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>