Self-check questions
Write your answers first, then open the answers to check them.
- Where are objects stored and where are reference variables stored?
- What is a memory leak in C++? Why is it less common in Java?
- When does an object become eligible for garbage collection?
- What happens when you call a method on a
nullreference?
Show answers
Objects, with their attributes, are stored on the heap. Local variables, including local reference variables, are stored on the stack, in the frame of the method that declares them. (A reference that is an attribute lives inside its object on the heap.)
In C++ a memory leak happens when memory allocated with
newis never released withdelete, so the program uses more and more memory. It is less common in Java because the garbage collector frees unreachable objects automatically. (Java programs can still leak if they keep references they no longer need, for example in a list that only grows.)When no live reference can reach it: for example after its last reference is set to
null, is pointed at another object, or goes out of scope when a method ends.A
NullPointerExceptionis thrown at run time, and the program stops unless the exception is handled. Prevent it by making sure the reference points to an object, or by checkingif (s != null)before using it.
Practice exercises
- Draw stack and heap diagrams for the code in the garbage collection example in 3.2.2, after each line.
- Create 1000 Student objects in a loop, then set the array reference to null. Explain which objects become eligible for GC.
- Write a short program that triggers a
NullPointerException, then fix it with a null check.