Head First Java: Chapter-9 summary

Life and Death of an Object

Tharaka Dissanayake
3 min readJul 17, 2022

Objects are saved in the heap of the memory. Methods and local variables stay on the stack of JVM. Therefore local variables are also known as stack variables.

Instance variables are part of the objects. So each instance (object) can store its values for the instance variables. Therefore instance variables are called fields.

The above example has three methods. The “doStuff()” method is called the “go(int x)” method, and the go method calls the tocrazy() method. Then When another class calls the doStuff() method, it comes to the top of the stack. The doStuff() method calls to go(int x) method. So the go(int x) method comes to the top of the stack. The go(int x) method calls to the crazy() method, which then comes to the top of the stack. Finally, the stack can be seen as follows.

When creating an object, there should be a reference to it. The object goes to the memory heap, and its reference goes to the stack.

Values of an object’s instance variables live inside the object. So when space is allocated for the object, JVM must consider its instance variables. No matter instance, variables are primitive. (Java will allocate 32 bits for the int variable if it is an int variable.) If this instance variable is an object reference, it will allocate space only for reference rather than allocating space for the object.

Constructors

A constructor has the code that runs when you instantiate an object. In other words, the code runs when you say new on a class type. Every class you create has a constructor, even if you don’t write it yourself. Constructors run before the object can be assigned to a reference. Constructors are used to initialising the instance variables. Java will create a default constructor for a class if we do not declare a constructor. Constructors are not inherited. But they can be overloaded. Also, there can be one or more constructors for a class.

Scope and life of the local variables

A local variable is alive as long as its Stack frame is on the stack. If the frame is removed (after execution of the method), the local variable will be removed with the frame. The local variable is in scope only within the method in which the variable was declared. When its method calls another, the variable is alive but not in scope until its method resumes.

Scope and life of the reference variables

Rules for the local variable are identical for the reference variables. Without object reference, an object can’t live on the heap. Objects will be killed with the following matters.

  1. The reference goes out of scope permanently.
  2. Assign the reference to another object.
  3. Explicitly set the reference to null.

--

--

Tharaka Dissanayake
Tharaka Dissanayake

No responses yet