Reputation: 4564
Another exam question that makes me confused:
public String makinStrings() {
String s = “Fred”;
s = s + “47”;
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
}
the question is: "How many String objects will be created when this method is invoked?"
correct answer is supposed to be 3 but I counted more:
Fred
47
Fred47
ed4
ED4
is 3 really the correct answer? If so - why?
Upvotes: 0
Views: 96
Reputation: 41
String constants are instantiated at the moment the class is instantiated. Because of that, the strings "Fred" and "47" are instantiated before the method is invoked, and not during method invocation.
This article explains it : The String Constant Pool
But I will refine it a little more: the Java Virtual Machine Specification specifies that the constants "Fred" and "47" be placed as entries in the String Constant Pool. ( java SE specs, loading and linking ).
This happens when the class is loaded.
Another point to focus here: the question is how many objects are instantiated.
So,
String s = "Fred" : doesn't instantiate a new String object, only uses a reference from the internalized "Fred" constant.
s = s + "47" : the '+' operator implies a concatenation operation; the result of that concatenation is a new String object. So, 1 String instantiated. The "47" was loaded with the Class...
s = s.substring(2,5): the method definition specifies that a new string object must be returned ( String.substring javadoc ), so, 2 Strings instantiated.
Even if the implementation ( this, for example the openJDK java.lang.String implementation) may use some kind of constructor to only refer to a portion of the character array that have the String internal value, the result is a new String, even if a kind of "lazy" one.
s = s.toUpperCase(): same here, the toUpperCase method must return a new String. So, 3 Strings instantiated.
And finally, s.toString() returns a representation of the object as a String. Since a String is already a String, s.toString() returns only the exact same String object...
Upvotes: 1
Reputation: 1271
3 objects:
Fred
Fred47
ED4
s = s + “47”;
47 won't be created on the String pool
s = s.substring(2, 5);
Shouldn't create a separate string but will follow flyweight pattern and internally point to the same string.
Upvotes: 0