• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String Objects

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
bacon. tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic