Forums Register Login
Strings comparison

But why is this?

[ April 25, 2007: Message edited by: Tore Sagen ]
I think the second example adds another reference to the same string "ab".

But the frist example, why doesn't "a"+"b" (first to evaluate, evaluates to "ab") refer to the same string object as "ab"?
The JVM and compiler use the same object for two identical Strings, if they can recognise them before runtime.
Obviously the if is stopping the JVM recognising that at class loading time.

I tried it, and it didn't print either. Which JVM are you using? Mine is:-

[Campbell@dhcppc0 disk]$ java -version
java version "1.6.0_01"
Java(TM) SE Runtime Environment (build 1.6.0_01-b06)
Java HotSpot(TM) Client VM (build 1.6.0_01-b06, mixed mode, sharing)
[Campbell@dhcppc0 disk]$


Edit: When I said it didn't print either, I meant neither a + b == "ab" nor c == "ab" came up as true.
[ April 25, 2007: Message edited by: Campbell Ritchie ]
(a+b == "ab")//prints nothing Because the == operator is not comparing the contents of the Strings instead it is comparing the address of the two Strings. Also String objects are immutable you can reassign references, but you can't change the contents of a String.

String c = a+b // Here you are creating a new String the new String will equal "ab" than == will print true;
if (c == "ab")//print true
But this is the wrong way of comparing String. Use c.equal("ab") instead dont forget String are Immutable.

1)dont use == to compare String instead use oneString.equals("anotherString").

2)a+b creates a temporary object and increases garbage collection than you should use StringBuffer to concat you string.

hope this help

[ April 25, 2007: Message edited by: Reda Mokrane ]
[ April 25, 2007: Message edited by: Reda Mokrane ]

Originally posted by Reda Mokrane:

1)dont use == to compare String instead use oneString.equals("anotherString").

according to Reda clarification on this

hope this line of code make sense to you..
Yes, that behaviour is what you would expect. "zg" has the same contents as "z" + "g". That is what the equals() method tests for. Whenever you use an equals method, it is worth checking in that class' API documentation about equals. It should be shown as a method in its own right; if it appears in the box headed "inherited from Object" then it checks to see whether the two are the same object. See the equals method in the API for java.lang.Object.
It's a pleasure to see superheros taking such an interest in science. And this tiny ad:
Rocket Oven Kickstarter - from the trailboss

This thread has been viewed 1001 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 15, 2018 23:02:29.