Chapter 9. Life and Death of an Object: Constructors and Garbage Collection
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.