String Objects and the + Operator
For convenience in working with strings, Java also uses the + and += operators to indicate concatenation. When the compiler finds an expression in which a string appears in association with a + operator, it turns all items in the expression into strings, concatenates the strings, and creates a new String object. However, remember that expressions are evaluated left to right, so if the compiler sees a numeric operation before the String, it will carry out that operation before the conversion to a String. You can see this in action in the following code, which produces "101 is the result", not "1001 is the result".
int n = 1 ; System.out.println( 100 + n + " is the result ");
The compiler has a complete set of conventions used to turn primitives and objects into strings, but the only operators that can be used are the + and += operators.
The methods used to turn primitives into strings are found in the wrapper classes that Java has for each primitive. (Wrapper classes are discussed in detail in Chapter 11, "Standard Library Utility Classes.") For instance, in the following code fragment, the compiler knows to use the toString method in the Float class to create a String representation of the pi primitive. It also knows how to add the Unicode character for the Greek letter pi to the String:
1. float pi = 3.14159f ; 2. String tmp = "Pi = " + pi + " or " + '\u03c0' ;
Objects and toString()
The root of the Java object hierarchy, the Object class, has a toString() method that returns a descriptive string. Therefore, every object has a toString method by inheritance. This default toString method produces a rather cryptic result, so many of the standard library classes implement a toString method that is more appropriate for the particular class. The net result is that the compiler can always use the + operator in any combination of strings and objects.
Strings Are Immutable
The contents of a String object cannot be changed. Take the following code:
1. String filename = new String( "mystuff" ) ; 2. filename += ".txt" ;
It looks as if we are changing a String object. What is actually happening is that there is a String object created in line 1 with a reference in the variable named filename. In line 2, the contents of that String are concatenated with the literal ".txt" and a reference to the new String object is stored in the variable filename.
Questions involving the immutability of String objects frequently cause trouble for beginning Java programmers. Chapter 11 contains more examples and practice questions on this subject.
The null Value and Strings
The Java mechanism that adds various items to create strings can recognize that a reference variable contains the special value null, instead of an object reference. In that case, the string "null" is added.