Java Reference
In-Depth Information
StringBuffer sb = new StringBuffer();
sb.append('H');
sb.append('a');
System.out.println(sb);
This works, but it's ugly. There are ways to avoid the verbosity of this approach. You can force the
+ operator to perform string concatenation rather than addition by ensuring that at least one of its
operands is a string. The common idiom is to begin a sequence of concatenations with the empty
string (""), as follows:
System.out.print("" + 'H' + 'a');
This idiom ensures that subexpressions are converted to strings. Although useful it is a bit ungainly
and can lead to some confusion itself.
Can you guess what the following statement prints? If you aren't sure, try it:
System.out.println("2 + 2 = " + 2+2);
As of release 5.0, you also have the option of using the printf facility:
System.out.printf("%c%c", 'H', 'a');
In summary, use the string concatenation operator with care. The + operator performs string
concatenation if and only if at least one of its operands is of type String ; otherwise, it performs
addition. If none of the values to be concatenated are strings, you have several choices: prepend the
empty string; convert the first value to a string explicitly, using String.valueOf ; use a string
buffer; or if you are using release 5.0, use the printf facility.
This puzzle also contains a lesson for language designers. Operator overloading, even to the limited
extent that it is supported in Java, can be confusing. It may have been a mistake to overload the +
operator for string concatenation.
< Day Day Up >
 
 
Search WWH ::




Custom Search