0

Below is a Java program.

 public String makinStrings() {
 String s = “Fred”;
 s = s + “47”;
 s = s.substring(2, 5);
 s = s.toUpperCase();
 return s.toString();
 }

How can I find out how many String object is created in the String pool. I think there are 4 objects created which are - "Fred" , "Fred47" , "ed4" , "ED4". Is this correct assumption?

1 Answers1

1

For the Java version 7:

  • Due to this topic the + operator creates new object
  • Due to String reference and this topic:
    • substring() creates a new string because String is immutable
    • toUpperCase() creates a new string because String is immutable
    • toString() does not create a new string but returning him itself

Assigning the "Fred" at the beginning won't create a new object since it will be taken from literal pool

To sum up - 3 Strings has been created with every method call. The string is an object so returning it does not create new - it is done by reference.

Community
  • 1
  • 1
m.antkowicz
  • 13,268
  • 18
  • 37
  • Why do you think `toUpperCase()` doesn't create a new string? – xehpuk Oct 11 '15 at 03:15
  • Of course it will - I've been suggested with no explicit information in the reference what was acually wrong. The question is a duplicate of http://stackoverflow.com/questions/7370593/how-many-string-objects-will-be-created btw but I cannot flag it for some weird reason - I edited answer to the proper one (cause I also cannot delete it now... uhh). Thanks for the warning anyway – m.antkowicz Oct 11 '15 at 03:27