Temporary Objects

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Line of code: Correct or Not?
String line = "The Sky was like a WaterDrop" ; correct
String a = line.toLowerCase(); correct
String b = toLowerCase( line ); NOT correct
String c = toLowerCase( "IN THE SHADOW OF A THORN"); NOT correct
String d = "Clear, Tranquil, Beautiful".toLowerCase(); correct
System.out.println( "Dark, forlorn...".toLowerCase() ); correct

Temporary Objects

The "correct" answer for the last two lines might surprise you, but those lines are correct (although perhaps not very sensible.) Here is why:

String d     =  "Clear, Tranquil, Beautiful".toLowerCase();
                 ---------------+-----------     ---+---
   |                            |                   |
   |                            |                   |
   |             First:  a temporary String         |
   |                     object is created          |
   |                     containing these           |
   |                     these characters.          |
   |                                                |
   |                                               Next: the toLowerCase() method of
   |                                                     the temporary object is
Finally:  the reference to the second                    called. It creates a second 
          object is assigned to the                      object, containing all lower
          reference variable, d.                         case characters.

The temporary object is used to construct a second object. The reference to the second object is assigned to d. Now look at the last statement:

System.out.println( "Dark, forlorn...".toLowerCase() );

A String is constructed. Then a second String is constructed (by the toLowerCase() method). A reference to the second String is used a parameter for println(). Both String objects are temporary. After println() finishes, both Strings are garbage.

(There is nothing special about temporary objects. What makes them temporary is how the program uses them. The objects in the above statement are temporary because the program saves no reference to them. The garbage collector will soon recycle them.)

QUESTION 23:

Tedious review:

  • Can an object reference variable exist without referring to an object?
  • Can an object exist without an object reference variable that refers to it?