class ClassA {
ClassB mem1 = new ClassB();
ClassB mem2 = new ClassB();
}
class ClassB {
}
public class Sample {
public static void main(String[] args)
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
Java Garbage Collection Basics
In this context, when obj1 = null; is processed there are no references to the object of type ClassA to which it points, and so it is eligable for garbage collection. The ClassB object, mem1 however still has a reference in the form of obj2 and so is kept at least until the line obj2 = null; is executed.