• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Madhan Babu B
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • 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. }
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
thank you!!!
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • 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...
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!