Java Reference
In-Depth Information
Many hands make light work
99 hands make light work
fifty five is 55
10 is ten
How It Works
The first line of output is quite straightforward. It simply joins the three string values stored in the
String variables firstString , secondString , and thirdString into a single string, and stores
this in the variable myString .
The second line of output is a use of the + operator we have used regularly with the println()
method, but clearly something a little more complicated is happening here. This is illustrated below:
Behind the scenes, the value of the variable numHands is being converted to a string that represents this
value as a decimal number. This is prompted by the fact that it is combined with the string literal, " " .
Dissimilar types in a binary operation cannot be operated on, so one operand must be converted to the type
of the other if the operation is to be possible. Here the compiler arranges that the numerical value stored in
numHands is converted to type String to match the type of the right operand of the + operator. If you look
back at the table of operator precedences, you will see that the associativity of the operator + is from left to
right, so the strings are combined in pairs starting from the left, as shown in the diagram.
The left-to-right associativity of the + operator is important in understanding the next two lines of
output. The two statements involved in creating these strings look very similar. Why does " 5 + 5 " result
in 55 in one statement, and 10 in the other? The reason is illustrated below.
Search WWH ::




Custom Search