Java Reference
In-Depth Information
When coding a numeric expression, use parentheses freely when in doubt as to
the valid form and evaluation of a numeric expression. For example, if you wish to
have Java divide 6 * D by 5 * P, the expression may be written correctly as 6 * D / 5
* P, but it also may be written in the following manner:
(6 * D) / (5 * P)
Using Parentheses When Coding Numeric or Conditional
Expressions
When coding numeric or conditional expressions, use parentheses
freely if you are unsure about operator precedence and the form
of a valid expression. Using parentheses helps to provide clarity
when the expression is evaluated.
For more complex expressions, Java allows parentheses to be contained
within other parentheses. When this occurs, the parentheses are said to be
nested . In this case, Java evaluates the innermost parenthetical expression first,
then goes on to the outermost parenthetical expression. Thus, 18 / 3 * 2 + (3 *
(2 + 5)) is broken down in the following manner:
18 / 3 * 2 + (3 * (2 + 5))
18 / 3 * 2 + (3 * 7)
18 / 3 * 2 + 21
6 * 2 + 21
12 + 21
33
When coding expressions, be sure to avoid two common errors. First, check
that you have surrounded the correct part of an expression with parentheses.
Second, check that you have balanced the parentheses by verifying that the
expression has as many close parentheses as open parentheses.
Construction of Error-Free Expressions
If you have written an expression observing the order of precedence rules,
Java can translate the expression without generating any error messages. This,
however, is no guarantee that Java actually will be able to evaluate it. In other
words, although a numeric expression may be formed in a valid fashion, Java
may not be able to evaluate it because of the data type of the numbers involved
or some other logic error. In situations where error conditions arise during com-
pilation, Java will display an error message.
Applying the following rules when coding expressions should help you avoid
such hazards:
1. Do not attempt to divide by zero.
2. Do not attempt to determine the square root of a negative value.
3. Do not attempt to raise a negative value to a non-integer value.
Search WWH ::




Custom Search