Unit 3 · OOP Concepts

3.2.3Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. Where are objects stored and where are reference variables stored?
  2. What is a memory leak in C++? Why is it less common in Java?
  3. When does an object become eligible for garbage collection?
  4. What happens when you call a method on a null reference?
Show answers
  1. 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.)

  2. In C++ a memory leak happens when memory allocated with new is never released with delete, 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.)

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

  4. A NullPointerException is 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 checking if (s != null) before using it.

Practice exercises

  1. Draw stack and heap diagrams for the code in the garbage collection example in 3.2.2, after each line.
  2. Create 1000 Student objects in a loop, then set the array reference to null. Explain which objects become eligible for GC.
  3. Write a short program that triggers a NullPointerException, then fix it with a null check.