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.
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...!!)
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.