The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.
23. Temporary Objects
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
The "correct" answer for the last two lines might surprise you, but those
lines are correct (although perhaps not very sensible.) Here is why:
Temporary Objects
Temporary Objects
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 as a parameter for println()
. Both String
objects are temporary. After println()
finishes, both String
s 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:
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?