Download presentation
Presentation is loading. Please wait.
Published byScot Hicks Modified over 9 years ago
1
Chapter 9 Life & Death of an Object Stacks & Heaps; Constructors Garbage Collector (gc)
2
The Stack and the Heap – where things Live Crucial to understanding what happens when creating an object Need to learn about where everything lives, and for how long, in Java The Stack and the Heap The Heap – where objects live The stack – where method invocations and local variables live.
3
Objects and Variables All objects lives on the garbage-collectible heap Where do variables live? – Depends on what type of variable it is – Instance Variables & local variables Local variables known as stack variable. Methods that are called and local variables live on the stack.
4
Instance v. Local – page 236 Instance – declared inside a class, not inside a method – Represent fields that each individual object has Local Variables – declared inside a method – Temporary; live only as long as the method is on the stack; as long as method hasn’t reached the closing curly brace
5
The Stack Methods are Stacked – When you call a method, it lands on the top of a call stack. – The new thing is pushed onto the stack frame, which holds the state of the method including the line of code that is executing, and any LOCAL variables. – Method at the TOP of the stack is always the currently-running method for that stack.
6
Stack Scenario Code and illustration on page 237 Look through each line of code Methods are called and put on the stack
7
What about local variables that are Objects? Remember, a non-primitive variable holds a reference to an object, not the object itself. Objects live on the heap If the local variable is a reference to an object, only the variable (reference /remote control) goes on the stack. Example – page 238
8
Bullet points Java has 2 areas of memory – stack & heap Instance variable declared inside a class, outside of a method Local variables declared inside a method or method parameter All local variables live on the stack, in the frame corresponding to the method declared Object reference variables work like primitive variables All objects live in the heap
9
Local v. Instance Variables If local variables live on the stack, where do instance variables live? When creating an object, how much space is needed for an object and the instance variables? Values of an object’s Instance variables live inside the object. Java makes space. What if instance variable is an object? Java makes the space when instance variable is assigned a value.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.