Chapter 3: Assignments


Stack and Heap—Quick Review

For most people, understanding the basics of the stack and the heap makes it far easier to understand topics like argument passing, polymorphism, threads, exceptions, and garbage collection. In this section, we'll stick to an overview, but we'll expand these topics several more times throughout the book.

For the most part, the various pieces (methods, variables, and objects) of Java programs live in one of two places in memory: the stack or the heap. For now, we're going to worry about only three types of things: instance variables, local variables, and objects:

  • Instance variables and objects live on the heap.

  • Local variables live on the stack.

Let's take a look at a Java program, and how its various pieces are created and map into the stack and the heap:

  1. class Collar { }  2.  3. class Dog {  4.   Collar c;         // instance variable  5.   String name;      // instance variable  6.  7.   public static void main(String [] args) {  8.  9.     Dog d;                         // local variable: d 10.     d = new Dog(); 11.     d.go(d); 12.   } 13.   void go(Dog dog) {               // local variable: dog 14.     c = new Collar(); 15.     dog.SetName("Fido"); 16.   } 17.   void setName(String dogName) {   // local var: dogName 18.     name = dogName; 19.     // do more stuff 20.   } 21. } 

Figure 3-1 shows the state of the stack and the heap once the program reaches line 19. Following are some key points:

image from book
Figure 3-1: Overview of the Stack and the Heap

  • Line 7—main() is placed on the stack.

  • Line 9—reference variable d is created on the stack, but there's no Dog object yet.

  • Line 10—a new Dog object is created and is assigned to the d reference variable.

  • Line 11—a copy of the reference variable d is passed to the go() method.

  • Line 13—the go() method is placed on the stack, with the dog parameter as a local variable.

  • Line 14—a new Collar object is created on the heap, and assigned to Dog's instance variable.

  • Line 17—setName() is added to the stack, with the dogName parameter as its local variable.

  • Line 18—the name instance variable now also refers to the String object.

  • Notice that two different local variables refer to the same Dog object.

  • Notice that one local variable and one instance variable both refer to the same String Aiko.

  • After Line 19 completes, setName() completes and is removed from the stack. At this point the local variable dogName disappears too, although the String object it referred to is still on the heap.




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net