How many objects will be eligible for garbage collection after the execution of line 9 in the following code?
Solution : This code creates 16 objects of type Double. Out of which, 15 Double objects are created by the iterations of the nested for loops at lines 6 and 7, and one more Double object is created at line 5. The very first iteration of the loop makes the object created at line 5 eligible for garbage collection. With each iteration of the loop, a new object is created and assigned to 'x', and the old (or previously created) object becomes eligible for garbage collection. Only the most recently created object (for i=4 and j=2) is not eligible for garbage collection.
Thus, out of the created 16 objects (including the one created at line 5), a total of 15 objects have become eligible for garbage collection after the execution of line 9.
Actually, as explained in the earlier paragraph, each iteration of the loop (line 8) makes the previously created object eligible for garbage collection. Thus, by the time both nested loops finish their execution (before execution of line 9), a total of 15 objects have become eligible for garbage collection. The execution of line 9 itself does not affect garbage collection in any way. Want to know more?
You can read more about garbage collection at -
Source : "Facebook community"