CPSC 124, Spring 2017: Sample Answers to Quiz #5

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. In Java, "a variable can never contain an object, only a pointer to an object." Explain what this means and what it has to do with the heap. A picture could be useful.

Answer. A pointer to an object is the address of the location in memory where the object is stored. A variable will only store the address of the object, which is enough information for the computer to be able to find the object. The object itself is actually stored in the heap, which is a region of the computer's memory. When an object is created with the new operator, the computer allocates memory for that variable on the heap, and the return value of new is a pointer to the newly created object. So, after a statement such as Point pt = new Point(); we can visualize the situation as something like this:

Question 2. What is the meaning of null, in Java?

Answer. null is a special value that can be stored in a variable of object type to mean that the variable does not point to any object.

Question 3. Write a complete class definition containing: one private instance variable of type int, a method that can be used to add a specified value to that instance variable, and a getter method for reading the value of the variable.


            public class RunningSum {
                private int sum;
                public void add(int number) {
                    sum = sum + number;
                public int getSum() {
                    return sum;

Question 4. Using the class from the previous problem, write a Java statement or statements that will create a new instance of the class and declare a variable that points to that object.


            RunningSum sum = new RunningSum();