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.
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.
Here are some details about how the reference variable and the two objects relate:
Statement | Action |
---|---|
str = new String( |
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( |
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. |
(Look at the picture:) When the Calico Cat is constructed, what happens to the reference to the Gingham Dog?