mucashinto mucashinto - 1 month ago 24
Java Question

Is everything null in Java eligible for garbage collection?

Just wondering if that when you set

obj1 = null;


the object is eligible for gc, is it also true that everything with a null value is technically eligible also?

I'm particularly wondering about arrays, say if you have something like

[obj1, obj2, null, obj3, null, obj 4, obj5]


Can the gc run and remove the null object so the elements are empty?

Answer

There is no "null object", and null is the closest thing that exists to an empty reference. The key definitions are in the Java Language Specification, 4.3.1. Objects:

An object is a class instance or an array.

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

obj1 = null; changes the reference variable obj1 to be null. If it previously referred to an object it no longer does so.

There may be other references that refer to that object, so that the object remains reachable, and the garbage collector will leave it alone. If obj1 was the last reference to the object, it is no longer reachable, and is eligible for finalization.