in discussion SCJP2 Discussion / memory related » how many strings are created?
Reference javaranch thread -> http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=042205&p=1
How many String Objects are created when executing the following code?
11. public String makinStrings( ) { 12. String s = "Fred"; // this line creates one object 13. s = s + "47"; // this line creates two objects 14. s = s.substring( 2, 5); // this line creates one object 15. s = s.toUpperCase( ); // this line creates one object 16. return s.toString() ; 17. }
Though many ranchers answered already (a seems to be correct answer is 3), the perfect explanation
given by Jim Yingst is here:
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.





