go to previous page   go to home page   go to next page hear noise

Answer:

How many objects were created by the program?

TWO, one for the dog, one for the cat.

How many reference variables does the program contain?

ONE, which first refers to the dog, then refers to the cat.

Reference Variable Reused

Let us look at some of the details involved in doing this. Here is the program, again:


class EgString3
{
  public static void main ( String[] args )
  {
    String str;
     
    str   = new String("The Gingham Dog");
    System.out.println(str);

    str   = new String("The Calico Cat");
    System.out.println(str);
   }
}

Here is a diagram that shows the one reference variable str and the two objects. The variable can refer to only one object at a time. It first refers to the dog object, and then to the cat object.


Two Objects but one Reference Variable

Here are some details about how the reference variable and the two objects relate:

Statement Action
str = new String("The Gingham Dog"); Create the FIRST object.
Put a reference to this object into str
System.out.println(str); Follow the reference in str to the FIRST object.
Get the data in it and print it.
str = new String("The Calico Cat"); Create a SECOND object.
Put a reference to the SECOND object into str .
At this point, there is no reference
to the first object.
It is now "garbage."
System.out.println(str); Follow the reference in str to the SECOND object.
Get the data in it and print it.

QUESTION 12:

(Look at the picture:) When "The Calico Cat" object is constructed, what happens to the reference to "The Gingham Dog" object?