My friend sent me a question he saw in one mock exam for the Java certification about string objects:
String makeStrings(){
String s = "HI";
s = s + "5";
s = s.substring(0,1);
s = s.toLowerCase();
return s.toString();
}
How many string objects will be created when this method is invoked?
The correct answer the exam gave was 3. But I think it's five.
"HI"
"5"
"HI5"
"H"
"h"
Am I wrong?
解决方案
String makeStrings() {
String s = "HI"; //String literal
s = s + "5"; //concatenation creates new String object (1)
s = s.substring(0,1); //creates new String object (2)
s = s.toLowerCase(); //creates new String object (3)
return s.toString(); //returns already defined String
}
With respect to the concatenation, when creating a new String,JVM uses StringBuilder, ie:
s = new StringBuilder(s).append("5").toString();
toString() for a StringBuilder is:
public String toString() {
return new String(value, 0, count); //so a new String is created
}
substring creates a new String object unless the entire String is indexed:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex)
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
toString() does NOT create a new String:
public String toString()
{
return this;
}
toLowerCase() is a pretty long method, but suffice it to say that if the String is not already in all lowercase, it will return a new String.
Given that the provided answer is 3, as Jon Skeet suggested, we can assume that both of the String literals are already in the String pool. For more information about when Strings are added to the pool, see Questions about Java's String pool.