Object lifecycle describes how an object is created, used, becomes unreachable, and is eventually cleaned up.

Lifecycle

Class loaded
Object allocated
Constructor initializes state
Object is used
References are removed
Object becomes unreachable
Garbage collector may reclaim memory

Object Creation

FeatureFlag darkMode = new FeatureFlag();

This does a few things:

Reference vs Object

darkMode is not the object. It is a reference to the object.

Stack                     Heap
darkMode reference  --->   FeatureFlag object

Stack

The stack stores:

It is fast and automatically managed when methods return.

Heap

The heap stores:

Objects live until they become unreachable and the garbage collector removes them.

Garbage Collection

An object becomes eligible for garbage collection when no live reference can reach it.

FeatureFlag darkMode = new FeatureFlag();
darkMode = null;

If no other reference points to that object, it is eligible for cleanup.

Interview Notes