Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question..." Watch "question..." New topic


Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
How many String objects are created when we run the following code.

String s1,s2,s3,s4;
s1 = "Hello";
s2 = s1;
s3 = s2 + "Pal";
s4 = s3;
can anyone explain the answer...
Deepak Jindal
Ranch Hand

Joined: Nov 16, 2000
Posts: 30
Two strings are created.
Actually java forms a pool of literal strings whenever a new string object is created. So every time, it has to form a new string object, it first checks its pool of literal strings. If the same string exists in the pool, it refers to the same string.
In our case, a string object is created for s1.
No string object is created for s2, as it refers to same object s1.
Since, strings are immutable another string object is created for s3.
No string object is created for s4, as said above.
The things would be different, if we say
String s2 = new String(s1)
In this case, another string object is created in the programmers space at compile time. (At run it checks for the existing pool of literal strings.) The string object in programmers space can be placed by calling the method intern() of the String class.
Sujit Kurtadikar
Ranch Hand

Joined: Dec 05, 2000
Posts: 68
3 Objects will be created when the given program is executed.
They are, "Hello" , "Pal" and "Hello Pal"
s2 =s1 will not create new object, but will refere to same object refered by s1 (and Object ref count of "Hello" will become 2)
s3 = s2+"Pal" -> first Object "Pal" will be created and then new Object "Hello Pal" will be created.
s4 = s3 will refer to same object refered by s3.
In this way 3 objects will be created.
object "Pal" is temporarily created, it will become eligible for Grarbage Collection after object "Hello Pal" is created.
Hope this will help you.
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
sujit is right...
i made the same mistake as you deepak!
I agree. Here's the link:
subject: question...
It's not a secret anymore!