Hi All ! Really this is a somehow a tricky question that i need a clear explnation to it, consider the following code (assumed inside some class method) :
//BUT if you change the first line to make the String world as final //second case
so my questions are: [Q1] why the output changes to "true" when variable world became final ? [Q2] Are string created using operator '+' are String object created on the heap ( as new String()) or on the String pool (as string literals) ? Thanks ...
- Mostafa Radwan -
M.Sc | SCJP 1.4
posted 12 years ago
Hi Mostafa Q2: Strings are created on Heap when + is used Q1: When we declare "final" variable then compiler knows that it is not going to be changed so it replaces its occurances with the value given to it. Now, if this happens then in case of final String world the .class file is written to have, String s1 = "hello" + "world"; String s2 = "hello" + "world"; Now, here "hello" and "world" both are created on the Literal pool and so the summation result as well. Hence we get s1==s2, BUT when the world is not final then s1 and s2 are different objects so s1==s2 returns false. Also, try s1.intern() == s2.intern() when we don't have String world as final. You should see 'true' output as intern() method returns the internal presentation of the string content which is string literal in our case and the literals are same... Regards Maulin