Video in progress

What does the garbage collector do, and what would happen without it?

The GC finds objects on the heap that nobody uses anymore and frees the memory they occupy. Without it you would have to free memory by hand as in C, and bugs like leaks and double frees would multiply.

📖 Answer

Java has new but no delete. The JVM figures out for itself when an object is no longer needed.

How does the GC know what is "not needed"? Through reachability: starting from the GC roots (local variables on thread stacks, static fields, JNI references), it follows references. An object that can't be reached is garbage.

What this gives you: no dangling pointers, no double free, simpler code.

There is a price too. The GC takes CPU time, in some phases the application stops (a stop-the-world pause), and memory is freed not immediately but when the GC runs.

Keep in mind: the GC manages only memory. Resources like files, sockets and DB connections you have to close yourself.