I have the following Java code:
public String makinStrings() {
String s = "Fred";
s = s + "47";
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
}
The question is somehow simple: how many String objects will be created when this method is invoked?
At the beginning I answered that 5 String objects are created, but the answer from my book says that only 3 objects are created and no explanation was given (this is a SCJP question).
From my point of view there are 5 objects:
“Fred”, “47”, “Fred47”, “ed4”, “ED4”.
I also found this question on a SCJP simulation exam, with the same answer 3.
“Fred” and “47” will come from the string literal pool. As such they won’t be created when the method is invoked. Instead they will be put there when the class is loaded (or earlier, if other classes use constants with the same value).
“Fred47”, “ed4” and “ED4” are the 3
Stringobjects that will be created on each method invocation.