go to previous page   go to home page   go to next page        


When a new reference is assigned to str it replaces the previous reference.


Details of the action:

  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. The reference in the variable can be used to find the object.
  6. If another reference is saved in the variable, it replaces the previous reference.
  7. If no variables refer 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 refered to by any reference variable. Since they cannot be found by the program, there is no reason for them to 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 so that the memory they are made of can be used again.


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