Java Reference
In-Depth Information
10 < 5 = = true
false = = true <-first scan, less than operator evaluated
false <-second scan, equality operator evaluated
If you have trouble following the logic behind this evaluation, use the fol-
lowing technique. Whenever a conditional expression is to be evaluated, scan the
expression from left to right two 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 <, >, <=,
or >=, perform the required operation: less than, greater than, less than or equal
to, greater than or equal to. Hence, 10 < 5 evaluated to false.
On the second scan, moving again from left to right, every time you
encounter the operators == and !=, evaluate for equality and nonequality. In the
above example, false does not equal true, which results in a false expression. You
will learn more about conditional expressions in later chapters.
Using Parentheses in Expressions
Parentheses may be used to change the order of operations. In Java, paren-
theses normally are used to avoid ambiguity and to group terms in a numeric or
conditional expression. The order in which the operations in an expression con-
taining parentheses are evaluated can be stated as follows: when parentheses are
inserted into an expression, the part of the expression within the parentheses is
evaluated first, then the remaining expression is evaluated according to the nor-
mal rules of operator precedence.
Use of Parentheses in Expressions
When parentheses are inserted into an expression, the part of the
expression within the parentheses is evaluated first, then the
remaining expression is evaluated according to the normal rules of
operator precedence.
If the first numeric expression example were rewritten with parentheses as
18 / (3 - 2) + 4 * 2, then it would be evaluated in the following manner:
18 / (3 - 2) + 4 * 2
18 / 1 + 4 * 2
18 + 4 * 2
18 + 8
26
Evaluating numeric expressions with parentheses should be done as follows:
make four scans from left to right within each pair of parentheses, and only after
doing this make the standard four passes over the entire numeric expression.
Evaluating conditional expressions with parentheses should be done as
follows: make two scans from left to right within each pair of parentheses, and
only after doing this make the standard two passes over the entire conditional
expression.
Search WWH ::




Custom Search