Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.5 Compound Arithmetic Expressions | 119

number. Instead, we must explicitly include any spaces that we need as part of the expres-
sion:


answer = "The results are: "+ 27 + ", "+ 18 + ", and "+ 9;


It is also important to note that the result of the original expression wasn’t


"The results are: 45 and 9"


Why doesn’t the subexpression 27 + 18 perform an integer addition? The answer lies in
the precedence rules. Let’s take a closer look at the evaluation of this expression. All of the
operators in the expression have the same precedence and thus are evaluated left to right.
The first operand is a string, so the first +is a concatenation. The second operand is converted
to a string and concatenated, giving the string


"The results are: 27"


as the result. This string becomes the first operand of the second +operator, so it is also a con-
catenation. The number 18 is thus converted to a string and concatenated with the result of
the first operator to produce a new string:


"The results are: 2718"


The third operator has two strings as its operands, so no conversion is necessary. It produces


"The results are: 2718 and "


The last operator then has a string as its first operand and an integer as its second operand.
The integer is converted to a string and concatenated to form the final result, which is as-
signed to answer.
As you can see from the preceding discussion, when an expression mixes strings and nu-
meric types, you must consider the entire expression in light of the precedence rules. Take
a look at the following expression and see if you can determine what its result is:


answer = 27 + 18 + 9 + " are the results."


If you think it is


"27189 are the results."


then you are forgetting the effect of the left-to-right evaluation precedence rule. Its ac-
tual result is


"54 are the results."

Free download pdf