This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Tricky String Concatenation . Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Tricky String Concatenation ." Watch "Tricky String Concatenation ." New topic

Tricky String Concatenation .

Mostafa Radwan

Joined: Sep 09, 2003
Posts: 25
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) :

//first case

//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
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
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...
I agree. Here's the link:
subject: Tricky String Concatenation .
It's not a secret anymore!