Java Reference
In-Depth Information
Java will reject the statement because a value (2) and a variable (myAnswer)
within the same expression must be separated by an arithmetic operator. The
statement can be written validly as:
response = 2 * myAnswer; //Valid statement
It also is invalid to use a String variable or String literal in a numeric expres-
sion. The following are invalid numeric expressions:
response = 72 + “BALANCE” / myValue;
response = “45” / myValue + “answer” - 19;
Evaluation of Numeric Expressions
As you form complex numeric expressions involving several arithmetic oper-
ations, it is important to consider the order in which Java will evaluate the
expression. For example, in evaluating the expression:
answer = 16 / 4 / 2
would the result assign 2 or 8 to the identifer, answer? The answer depends on
how you evaluate the expression. If you complete the operation 16 / 4 first, and
only then 4 / 2, the expression yields the value 2. If you complete the second
operation, 4 / 2, first, and only then 16 / 2, it yields 8.
Java follows the normal algebraic rules to evaluate an expression. The nor-
mal algebraic rules that define the order in which the operations are evaluated
are as follows: unless parentheses dictate otherwise, reading from left to right in
a numeric expression, all multiplications and/or divisions are performed first,
then all integer divisions, then all modular divisions, and finally all additions
and/or subtractions. Following these algebraic rules, Java would evaluate the
expression 16 / 4 / 2 to yield a value of 2.
Order of Operator Precedence
Unless parentheses dictate otherwise, Java evaluates expressions
and performs all operations in the following order:
1. multiplication and/or division
2. integer division
3. modular division
4. addition and/or subtraction
When multiple operations of the same kind exist, Java performs
the operations left to right.
This order of operator precedence, which defines the order in which
operators are evaluated, sometimes also is called the rules of precedence, or the
hierarchy of operations. The meaning of these rules can be made clear with
some examples.
Search WWH ::




Custom Search