Chapter 9. Life and Death of an Object: Constructors and Garbage Collection

image

Objects are born and objects die. You’re in charge of an object’s lifecycle. You decide when and how to construct it. You decide when to destroy it. Except you don’t actually destroy the object yourself, you simply abandon it. But once it’s abandoned, the heartless Garbage Collector (gc) can vaporize it, reclaiming the memory that object was using. If you’re gonna write Java, you’re gonna create objects. Sooner or later, you’re gonna have to let some of them go, or risk running out of RAM. In this chapter we look at how objects are created, where they live while they’re alive, and how to keep or abandon them efficiently. That means we’ll talk about the heap, the stack, scope, constructors, superclass constructors, null references, and more. Warning: this chapter contains material about object death that some may find disturbing. Best not to get too attached.

The Stack and the Heap: where things live

Before we can understand what really happens when you create an object, we have to step back a bit. We need to learn more about where everything lives (and for how long) in Java. That means we need to learn more about two areas of memory—the Stack and the Heap. When a JVM starts up, it gets a chunk of memory from the underlying OS and uses it to run your Java program. How much memory, ...

Get Head First Java, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.