Bom dia pessoal, estou fazendo o TestKiller e me deparei com a seguinte questão:
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
Eu marquei a letra E, um pouco em dúvida se poderia ser a F, contando com o s.toString() que não sei se é criado uma nova String.
Porém a resposta que ele me dá é a letra C… e eu não entendi isso.
No livro da Kathy tem o seguinte exemplo:
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
What is the output? For extra credit, how many String objects and how many
reference variables were created prior to the println statement?
Answer: The result of this code fragment is "spring winter spring summer". There
are two reference variables, s1 and s2. There were a total of eight String objects
created as follows: “spring”, “summer " (lost), “spring summer”, “fall” (lost), “spring
fall” (lost), “spring summer spring” (lost), “winter” (lost), “spring winter” (at this point
"spring” is lost). Only two of the eight String objects are not lost in this process.
Gostaria que vocês pudessem me ajudar a entender.
Obrigado,
Rafael.
