| |
Object References | page 6 of 10 |
It is possible to reassign an object reference to a new value. For example:
public class OneStringReference
{
public static void main (String[] args)
{
String str;
str = new String("first string");
System.out.println(str);
str = new String("second string");
System.out.println(str);
}
}
Run Output:
first string
second string
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 (see diagram below).
- 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 references. This is a commonly occurring situation, not usually a mistake. As a program executes, a part of the Java system called the "garbage collector" reclaims each lost object (the "garbage") so that memory it used can be available again.
Multiple objects of the same class can be maintained by creating unique reference variables for each object.
public class TwoStringReferences
{
public static void main (String[] args)
{
String strA; // reference to the first object
String strB; // reference to the second object
// create the first object and save its reference
strA = new String("first string");
// print data referenced by the first object.
System.out.println(strA);
// create the second object and save its reference
strB = new String("second string");
// print data referenced by the first object.
System.out.println(strB);
// print data referenced by the second object.
System.out.println(strA);
}
}
Run Output:
first string
second string
first string
This program has two reference variables, strA and strB. It creates two objects and places each reference in one of the variables. Since each object has its own reference variable, no reference is lost, and no object becomes garbage (until the program has finished running.)

Different reference variables that refer to the same object are called aliases. In effect, there are two names for the same object. For example:
public class Alias
{
public static void main (String[] args)
{
String strA; // reference to the object
String strB; // another reference to the object
// Create the only object and save its
// reference in strA
strA = new String("only one string");
System.out.println(strA);
strB = strA; // copy the reference to strB.
System.out.println(strB);
}
}
Run Output:
only one string
only one string

When this program runs, only one object is created (by new ). Information about how to find the object is put into strA . The assignment operator in the statement
strB = strA; // copy the reference to strB
copies the information that is in strA to strB . It does not make a copy of the object.
|