| 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 |
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.)
Review: