Can you explain the principle of automatic memory management in Java and how it cleans up unused objects?
sobes.tech AI
Answer from AI
In Java, automatic memory management is implemented through a garbage collector (GC). When objects are created, they are placed in the heap. The garbage collector periodically checks which objects are no longer reachable from active parts of the program (for example, from the call stack or static references).
If an object has no references, it means it is not used and can be removed, freeing up memory. This allows the programmer not to worry about manual memory deallocation, reducing the likelihood of errors such as memory leaks or double freeing.
Working principle:
- Objects are created and live in the heap.
- GC tracks references to objects.
- Objects without references are considered garbage.
- GC frees the memory occupied by such objects.
Example: if you have an object Person p = new Person(); and then p = null;, the Person object becomes unreachable and will be cleaned up by the garbage collector during the next run.