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.
new String()
calls do. Unless you think it is desirable to have a separate question every time the preconditions or the numerical answer is different, e.g. 1,2,3,4,5,... ad infinitum I really cannot see the point of your comment. – Freightagesubstring()
,toLowerCase() and
toString()` is what I meant. – Slopesubstring()
,toLowerCase()
, andtoString()
which the other question does not include. I do not know why this was closed... – SlopeString
and thechar[]
(possibly abyte[]
) that it wraps. – Everara