I think the answer depends on when String literals get created. Without checking the Java Language Specification to be sure, I believe String literals are created when the class is loaded. If this is right, then the answer is 3.
If however, String literals are created when a line containing that literal is executed, then the answer cannot be determined. All String literals are pooled, therefore if another piece of code containing "Fred" and "47" has already been executed, then these String literals will already exist and will not be recreated by this code. Therefore the answer would be 3. If however, neither of the literals had already been created, then the answer would be 5. And if only one of the literals had already been created the answer would be 4.
Assuming this is not a trick question and that the options of 'the answer cannot be determined' is not available, leads me to believe that my vague memory that String literals are created when the class is loaded is correct. So the answer is 3.
The SCJP answer is 5: two literals, the concatenation, and the calls to substring and toUpperCase. toString doesn't return a new String.
But outside of the SCJP exam, these kinds of questions are totally meaningless; in no sense does any "creating" of the two String literals happen while this code is executing. So the "real" answer is 3.
But as I suspect we're talking SCJP here, go with 5, and I'll move this to the SCJP forum, to boot.
The simple rule is Strings in java are immutable, that is they can never change. Even if it looks like you are changing a string you are not you are creating a new string, and / or moving the reference variable to the new string. If the String is a literal and the JVM finds a match in the pool then the reference simply points to the existing literal.
so 4 new objects created here! Hope this helps
be a well encapsulated person, don't expose your privates, unless you public void getWife()!
"47" is used in concatenation, that's right. But, it is also used as a literal, so it is put into the pool internally. So, "Fred" and "47" are in the pool, and "Fred47" is the third one. Then there is the substring and toUpperCase.
subject: How many String Objects are created by executing the following method