Java Fundamental Classes Reference

Previous Chapter 2
Strings and Related Classes
Next
 

2.3 String Concatenation

Java's string concatenation operator (+) provides special support for the String and StringBuffer classes. If either operand of the binary + operator is a reference to a String or StringBuffer object, the operator is the string concatenation operator instead of the arithmetic addition operator. The string concatenation operator produces a new String object that contains the concatenation of its operands; the characters of the left operand precede the characters of the right operand in the newly created string.

If one of the operands of the + operator is a reference to a string object and the other is not, the operator converts the nonstring operand to a string object using the following rules:

The following is a code example that uses the string concatenation operator:

// format seconds into hours, minutes, and seconds
String formatTime(int t) {
    int minutes, seconds;
    seconds = t%60;
    t /= 60;
    minutes = t%60;
    return t/60 + ":" + minutes + ":" + seconds;
}

Java uses StringBuffer objects to implement string concatenation. Consider the following code:

String s, s1, s2;
s = s1 + s2

To compute the string concatenation, Java's compiler generates this code:

s = new StringBuffer().append(s1).append(s2).toString()


Previous Home Next
StringBuffer Book Index StringTokenizer

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java