hi neha, chand here, according to me its only 3 objects are created when you invoke this method but in method many objects are created and lost.
correct me if im wrong.
Joined: Jun 17, 2007
hi chand, As per my understanding 5 objects are created and only one of the objects remains rest are all lost . So when the questions says how many objects are created when this method is invoked, which all objects are you counting. Can you please list them. Thanks.
As Collins well pointed out, only 4 String objects are created in code you posted.
Now, the toString() method does not create a new object in the case of the String class, but returns the String itself.
It is not this case, but the toUpperCase() method might also return the same object, instead of a new one, if all the characters of the String are already uppercase. Therefore...
...this would print true to the console because s and t are the same object.
So, be careful. And as I said before, 4 objects are created as far as I can see. [ September 16, 2007: Message edited by: Edwin Dalorzo ]
Joined: Jun 17, 2007
Hi, Can you please tell which all objects are lost?In such kind of question should we answer the total number of objects created or the objects created minus the objects lost. Another thing I guess you are not counting "47" as a String object. Please clarify.
Hi neha, I agree with you there were a total of 5 objects created as follows: 1. "Fred" 2. "47" (lost) 3. "Fred47" (Fred lost) 4. "ed4" (Fred47 lost) 5. "ED4" (ed4 lost)
According to me since each time the reference variable s is assigned with a newly created String object the original String object it was referring to is lost.So, I think finally only 1 of the 5 objects is not lost in this process and the final result is "ED4".
If the above code is modified as follows:
here too technically there are 5 objects created in the heap and 4 objects are lost but since the reference variable s is not reassigned with the values in lines 14 and 15 the final result would be "Fred47".
although at this point even I am not sure what answer is expected whether 1. total no. of objects created or 2. objects created - objects lost.