Java Reference
In-Depth Information
Example 15.18.1-1. String Concatenation
The example expression:
"The square root of 2 is " + Math.sqrt(2)
produces the result:
"The square root of 2 is 1.4142135623730952"
The + operator is syntactically left-associative, no matter whether it is determined by
type analysis to represent string concatenation or numeric addition. In some cases care
is required to get the desired result. For example, the expression:
a + b + c
is always regarded as meaning:
(a + b) + c
Therefore the result of the expression:
1 + 2 + " fiddlers"
is:
"3 fiddlers"
but the result of:
"fiddlers " + 1 + 2
is:
"fiddlers 12"
Example 15.18.1-2. String Concatenation and Conditionals
In this jocular little example:
Click here to view code image
class Bottles {
static void printSong(Object stuff, int n) {
String plural = (n == 1) ? "" : "s";
loop: while (true) {
System.out.println(n + " bottle" + plural
+ " of " + stuff + " on the wall,");
System.out.println(n + " bottle" + plural
Search WWH ::




Custom Search