Dúvida sobre Strings - Testkiller

Ola,

Quantas strings serão criadas no trecho de código abaixo:

11. public String makinStrings() { 12. String s = "Fred"; 13. s = s + "47"; 14. s = s.substring(2, 5); 15. s = s.toUpperCase(); 16. return s.toString(); 17. }

How many String objects will be created when this method is invoked?
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
Answer: C

:arrow: Por [size=18]Jim Yingst [/size]

JAVARANCH

http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=042205

Unfortunately this isn’t a very good test question, and it’s not representative of the questions you’ll get on the real exam. The problem is that the compile-time constants “Fred” and “47” have special behavior that’s more subtle then you need to know for the exam, and it’s ambiguous to say that they were “created” in the code. What happens is, String objects for “Fred” and “47” are created when the class is loaded, not when the method is run. And if the method is run more than once, “Fred” and “47” aren’t recreated - they just get re-used. So, if you run the method just once and exit, you get:

“Fred”, “47” created when class is loaded.
“Fred47”, “ed47”, “ED47” created when the method is run.

That’s 5 strings total.

If you run the method 5 times, you get

“Fred”, “47” created when class is loaded.
“Fred47”, “ed47”, “ED47” created when the method is run the 1st time
"Fred47", “ed47”, “ED47” created when the method is run the 2nd time
"Fred47", “ed47”, “ED47” created when the method is run the 3rd time
"Fred47", “ed47”, “ED47” created when the method is run the 4th time
"Fred47", “ed47”, “ED47” created when the method is run the 5th time

That’s 17 strings over 5 method calls.

Additionally, in the event that some other code has used the constants “Fred” or “47” before the method is called, those strings won’t be recreated at all. So it’s possible that the above code could create just 3 objects when run once, and 15 object when run 5 times.

Based on all this, you can guarantee that at least three String objects are created when the method is run, and at most, five. I would say that three String objects are created in the method, and two may be caused to be created when the class is loaded.

Ultimately I don’t think there’s any way to determine what the “best” answer is for this question because, the way it’s phrased, it’s ambiguous. I wouldn’t worry too much about it. The real exam won’t have a question like this anyway.

Cada ação sobre uma string cria uma nova.

(** não tenho muita certeza se o toString tbm se comporta assim.)

como o amigo acima disse estou em duvida entre D e E

Abraço!

Pessoal, a resposta é C.
O post que o duran copiou do javaranch explica o porque. Mas segundo o autor do post esse tipo de questão não cai na prova.