STACK AND HEAP AREA

The various pieces (methods, variables, and objects) of Java
programs live in one of two places in memory: the stack or the heap.

■ Instance variables and objects live on the heap.
■ Local variables live on the stack.

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("Aiko");
16. }
17. void setName(String dogName) { // local var: dogName
18. name = dogName;
19. // do more stuff
20. }
21. }


■ 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.

No comments:

Post a Comment