Java Reference
In-Depth Information
For example, the expression 18 / 3 - 2 + 4 * 2 is evaluated as follows:
18 / 3 - 2 + 4 * 2
6 - 2 + 4 * 2
6 - 2 + 8
4 + 8
12
If you have trouble following the logic behind this evaluation, use the fol-
lowing technique. Whenever a numeric expression is to be evaluated, read or
scan, the expression from left to right four different times and apply the order of
operator precedence rules outlined above each time you read the expression. On
the first scan, moving from left to right, every time you encounter the operators,
* and /, perform the required operation: multiplication or division. Hence, 18 is
divided by 3, yielding 6, and 4 and 2 are multiplied, yielding 8.
On the second scan, from left to right, perform all integer division. On the
third scan, from left to right, perform all modular division. This example
includes no integer division or modular division, so no operations are per-
formed.
On the fourth scan, moving again from left to right, every time you
encounter the operators, + and -, perform addition and subtraction. In this
example, 2 is subtracted from 6 resulting in 4. Then it is added to 8 for a total
of 12.
The following expression includes five arithmetic operators and yields a
value of -3.
5 * 3 % 2 + 7 / 2 - 7
15 % 2 + 7 / 2 - 7
<-end of first scan - multiplication performed
15 % 2 + 3 - 7
<-end of second scan - integer division performed
1 + 3 - 7
<-end of third scan - modular division performed
-3
<-end of fourth scan - addition and subtraction performed
In later chapters, you will add to the hierarchy of operations as you learn
about operators that manipulate single operands.
Conditional Expressions
A conditional expression is any expression that can be evaluated as true or
false. A conditional expression can include comparison operators, values, and
variables, as well as methods. The resulting data type after a conditional expres-
sion is evaluated is boolean. A conditional expression may contain String
variables and String literals. Table 3-8 on page 154 displays examples of
conditional expressions.
Conditional expressions are governed by validity and operator precedence
rules that are similar to those used with numeric expressions. Valid conditional
expressions that use two operands must separate the operands with a compari-
son operator. Unless parentheses dictate otherwise, conditional expressions are
evaluated from left to right. When multiple comparison operators exist in the
same statement, relational operators take precedence over equality operators. For
example, in the following expression, the operations are performed left to right,
resulting in a value of false:
Search WWH ::




Custom Search