• 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

How many String objects are created when the following method is invoked

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
11. public String makingStrings() {
12. String s="Fred";
13. s=s+"47";
14. s=substring(2,5);
15. s=s.toUpperCase();
16. return s.toString();
17. }
 
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


We can't tell that for sure without knowing the rest of the code, because the two string literals ("Fred" and "47") might have been added to the string pool before this method...
 
Madhan Babu B
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you!!!
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Madhan Babu B wrote:thank you!!!



You're welcome, but I'm not sure about the correctness of my answer. I don't know exactly when the String instances for the literals will be created, when the class is loaded, or when the code is executed, and now I don't have the time to investigate.

I hope someone wil correct me if I was wrong...
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Lorand Komaromi wrote:I hope someone wil correct me if I was wrong...



At the Java language level the object associated with a String literal already exists whenever the literal is used. This means that when,

String s="Fred";

is done no object is created. The object associated with "Fred" is defined to already exist. Of course this object must be created at some time but that's an implementation detail.
 
Whose rules are you playing by? This tiny ad doesn't respect those rules:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic