Actually, if you are reading K&B SCJP6 then it can be answered at Pg434. When a string literal is encountered, the string object is created when the class is loaded. SO Fred and 47 are compile time constants and are created when the class is loaded. But at run time Fred47,ed47 and ED47 are created. s.toString doesn't create a new string as that string is already there in the string pool. Read about Compile time Constants
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
String s = "fred" will be created when the class will be loaded and the reference will be added to the string pool so that if in future any satement uses "fred",it will just refer to the existing object in stead of making a new one ( although thats not needed here)
so, 3 objects at runtime will be created.
But, i have one question, what if they do not specify runtime or compilation time???Should i write 4 or i assume they are refering to the runtime scenario??
"I fear not the man who has practiced 10,000 kicks once, but I fear the man who has practiced one kick 10,000 times" - Bruce Lee
5 object will be created in all. They won't be asking runtime or compilation time.
Joined: Jul 05, 2009
"fred" athough resolved at compile-time, has an active reference at runtime. A class compiled today might be run after N years. If the literal is saved today it cannot stay till N years. As soon as the scope of compilation ends, literal's life ends. The reference needs to be resolved at runtime as well. So "fred" is spawned at runtime also. Then again it depends on the string-pool.
Joined: Aug 06, 2009
forgot there was also "47" hope,i won't get used to overlooking things