Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^114) | Arithmetic Expressions


3.5 Compound Arithmetic Expressions


The expressions we’ve used so far have contained at most a single arithmetic operator. We
also have been careful not to mix integer and floating-point values in the same expression.
Now we look at more complicated expressions—ones that are composed of several opera-
tors and ones that contain mixed data types.

Precedence Rules


Arithmetic expressions can be made up of many constants, variables, operators, and paren-
theses. In what order are the operations performed? For example, in the assignment statement

avgTemp = FREEZE_PT + BOIL_PT / 2.0;

is FREEZE_PT+ BOIL_PTcalculated first or is BOIL_PT/ 2.0calculated first?
The five basic arithmetic operators (+for addition, – for subtraction,*for multiplica-
tion,/for division, and %for modulus) and parentheses are ordered the same way mathe-
matical operators are, according to precedence rules:

Highest precedence: ()
++ (postfix increment) --(postfix decrement)
++ (prefix increment) --(prefix decrement)
unary + unary -
* / %
Lowest precedence: + -

In the preceding example, we first divide BOIL_PTby 2.0and then add FREEZE_PTto the result.
You can change the order of evaluation by using parentheses. In the statement

avgTemp = (FREEZE_PT + BOIL_PT) / 2.0;

FREEZE_PTand BOIL_PTare added first, and then their sum is divided by 2.0. We evaluate
subexpressions in parentheses first and then follow the precedence of the operators.
When multiple arithmetic operators have the same precedence, their grouping order(or
associativity) is from left to right. Thus the expression

int1 – int2 + int3

means (int1 – int2) + int3, not int1 – (int2 + int3). As another example, we would use the
expression

(double1 + double2) / double1 * 3.0
Free download pdf