Being eligible for GC
We already know that objects on the heap are removed when they are no longer needed. The right question to ask, then, would be, when are objects no longer needed?
That question is easy to answer but leads to a complex problem at the same time. Let’s first have a look at the answer: objects on the heap are no longer needed when they don’t have a connection to the stack.
Objects don’t have a connection to the stack when the stack doesn’t store the reference to the object in a variable. Here is a simple example:
Object o = new Object();
System.out.println(o);
o = null;
In the first line, we create the object, which gets created on the heap. The o
variable holds a reference to an object of type Object
on the stack. We use the object because we have the reference stored. In this case, we are printing it on the second line of the example, which is clearly a rather silly output since the toString()
method of Object
is only...