Can anyone explain the why the output is false for the following code ?
The output is false that means string created at LINE X has different bits than str1. I thought that if the same string (in our case "SCJP") is available in String constant pool, then str5 would simply be pointed to str1, that would save memory isn't it ?
Am I thinking wrong here ?
Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
A String MAY be taken from the String constant pool, but it doesn't have to be. Therefore the behaviour of == on Strings (like on any other object) will NOT be predictable unless you're intent on comparing actual references.
Joined: Aug 27, 2004
Jeroen, Thanks for the reply.I tried various combinations of string comparison and here is what I observed.
Whenever the == operator is operating on string objects which perform concatenation using + operator, the result is false, else the result is true.
Guys, this is my observation feel free to point out any combination which might prove this wrong.
Below is the code I wrote to test this, hopefully my fellow ranchers might benefit from this.
NOTE: the line x will result in true, because the concat function in String.java will check for string length which is zero in this case and will simply return this which is str6 object itself.
i think when you concatinate Str2 and Str23, reference of Str5 is different than Str1. If you try to compare Str5 with Str1 by "==", it will result "false". but with Str1.equals(Str5), it will return true.
Plz Correct me if i'm wrong.
Step one step back to learn more thing..!!<br />Post to learn<br />learn from mistake<br />take whatever i understand...!!!<br /> <br />SCJP 1.4, Brainbench Java 1 & 2.<br />SCWCD 1.4 (preparing...!!)
Joined: Aug 27, 2004
You are absolutely correct Hai Le, equals will give true
When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.