New Values in Reference Variables
Here is a further modification of the example program:
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);
}
}
|
The program does exactly what you would expect.
It writes out:
The Gingham Dog
The Calico Cat
Let us look at some of the details involved in doing this.
| 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. |
Notice that:
- Each time the new operator is used, a new object is created.
- Each time an object is created, there is a reference to it.
- This reference is saved in a variable.
- Later on, the reference in the variable is used to find the object.
- If another reference is saved in the variable,
it replaces the previous reference.
- If no variables hold a reference to an object, there is no way to find it, and it becomes
"garbage."
The word "garbage" is the correct term from computer science to use for objects
that have no referrences.
This is a commonly occuring situation, not usually a mistake.
As a program executes, a part of the Java system called the "garbage collector"
reclaims the lost objects (the "garbage") so that their memory can be used again.
|