Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question...

 
Anshuman Acharya
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sujit is right...
i made the same mistake as you deepak!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic