3.6 The Binary String Concatenation Operator +The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed. Non- String operands are converted as follows :
The result of the concatenation is always a new String object. The String class is discussed in Section 10.5. String theName = " Uranium"; theName = " Pure" + theName; // " Pure Uranium" String trademark1 = 100 + "%" + theName; // "100% Pure Uranium" (1) The integer literal 100 is implicitly converted to the string "100" before concatenation. This conversion is corresponds to first creating an object of the wrapper class Integer , which represents the integer 100 , and then creating a string from this object by using the toString() method supplied by this class: new Integer(100).toString(); Note that using the character literal '%' , instead of the string literal "%" in line (1) above, does not give the same result: String trademark2 = 100 + '%' + theName; // "137 Pure Uranium" Integer addition is performed by the first + operator: 100 + '%' , that is, (100 + 37) . Caution should be exercised as the + operator might not be applied as intended, as shown by the following example: System.out.println("We put two and two together and get " + 2 + 2); The above statement prints "We put two and two together and get 22" and not "We put two and two together and get 4" . The first integer literal 2 is promoted to a String literal "2" for the first concatenation, resulting in the String literal "We put two and two together and get 2" . This result is then concatenated with the String literal "2" . The whole process proceeds as follows: "We put two and two together and get " + 2 + 2 "We put two and two together and get " + "2" + 2 "We put two and two together and get 2" + 2 "We put two and two together and get 2" + "2" "We put two and two together and get 22" Both occurrences of the + operator are treated as string concatenation. A pair of parentheses might be in order to perform arithmetic addition, to convey the intended meaning of the sentence System.out.println("We put two and two together and get " + (2 + 2)); The compiler uses a string buffer to avoid the overhead of temporary String objects when applying the string concatenation operator ( + ), as explained in Section 10.6 on page 424. |