Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Objects

 
Anurag Blore
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

My answer is
String s = "Amar"; //First Object
s = s + "50";//Second Object
s = s.substring(2, 5);//Third Object
s = s.toUpperCase();//Four Object.

But I am not sure, Can anyone put his comment.

Thanks
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = "Amar"; A new string object is created in String pool "Amar" and is assigned to s. So count is 1.

s = s + "50"; Now a new string object "50" is created in String pool. So right now there are two string objects "Amar" and "50". Now because of + a new String object is created "Amar50" and is assigned to s. So after this statement there are 3 string objects. "Amar", "50" and "Amar50"

s = s.substring(2, 5); This will again create a new string object that has "ar5" and assing it to s. So now we have 4 string objects "Amar", "50", "Amar50" and "ar5"

s = s.toUpperCase(); This will again create a new String object "AR5" and assign it to s. So now we have 5 string obects "Amar", "50", "Amar50", "ar5" and "AR5"

return s.toString(); this will simply return s. and hence no string objects are created here.
So total result is 5 "Amar", "50", "Amar50", "ar5" and "AR5".
 
Anurag Blore
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Deepak,

Do you think in Java If there is a way we can write a program to check the
number of Objects created.

I am asking this question as this will be helpful for answering questions
for scjp exam.
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For Strings or other built-in clases, i dont think so you can do this. But for user defined clases you can do this by creating a static int counter and incrementing the counter in the constructor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic