Search code examples
javascjp

String objects created by a method


I'm doing a few mock test for my Oracle Certified Java Programmer certification. One of the question I found in a test is this one:

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

And the question is "How many String objects will be created when this method is invoked?". I'm counting 5: "Fred", "47", "Fred47", the substring "ed4" and the uppercased string "ED4", but the question answer is 3 objects (and the document where the test is doesn't have an explanation section). Can you point where is my error?


Solution

  • Sounds like the error is in the interpretation of "how many strings objects will be created when this method is invoked"

    You are correct in stating that five strings are involved; however, Strings are immutable, and two of those are constants that are compiled into the class containing the makinStrings() method. As such, two of your five pre-exist the call of the method, and only three "new" strings are created.

    The two constant strings exist in the class's constant pool, and were constructed at class load time.