Friday, May 24, 2013

Alias in Java

There is a very interesting question I got in the JAVA exam. Take a look at the following code, when does the object at line marked (0) will be the candidate for garbage collection?
String objA = “ABC”;  // (0)
String objB = a;

objA = “DEF”;  // (1)
objB = “GHI”;  // (2)
The answer is the line marked (2). Why not the line marked (1)? Because String objB is holding a reference of objA thus it will not get garbage collected. Until line marked (2), objB is assigned a new object, objA is no longer get reference by objB or no other objects are holding a reference of it, thus this is the great chance to dispose the object.

No comments: