A good answer might be:

No. The statement

str = value ;

is (apparently) asking that the primitive data type contained in value be placed in the reference variable str. This cannot be done.


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:

  1. Each time the new operator is used, a new object is created.
  2. Each time an object is created, a reference to it is created.
  3. Each object that exists in a computer system has a unique reference.
  4. This reference is usually saved in a variable.
  5. Later on, the reference in the variable is used to find the object.
  6. If another reference is saved in the variable, it replaces the previous reference.
  7. 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 for objects that are not referred to by any reference variable. Since they cannot be found (by your program) in effect they do not exist. This situation is common and not usually a mistake. As a program executes, objects are created. Then when they are no longer needed references to them are discarded. However, a part of the Java system called the garbage collector reclaims the lost objects (garbage) so that the memory they are made of can be used again.

QUESTION 10:

Can several objects of the same class exist in a program at the same time?