Java Reference
In-Depth Information
abcde
++++
5
Algebra:
Java:
m
=
-------------------------------------
m = (a + b + c + d + e) / 5;
The parentheses are required because division has higher precedence than addition. The
entire quantity (a + b + c + d + e) is to be divided by 5 . If the parentheses are erroneously
omitted, we obtain a + b + c + d + e / 5 , which evaluates as
abcd e
++++
---
Here's an example of the equation of a straight line:
Algebra:
Java:
y
=
mxb
+
y = m * x + b;
No parentheses are required. The multiplication operator is applied first because multipli-
cation has a higher precedence than addition. The assignment occurs last because it has a
lower precedence than multiplication or addition.
The following example contains remainder ( % ), multiplication, division, addition and
subtraction operations:
Algebra:
Java:
z = pr %q + w/x - y
z
=p*r%q+w/x-y;
6
1
2
4
3
5
The circled numbers under the statement indicate the order in which Java applies the op-
erators. The * , % and / operations are evaluated first in left-to-right order (i.e., they associ-
ate from left to right), because they have higher precedence than + and - . The + and -
operations are evaluated next. These operations are also applied from left to right . The as-
signment ( = ) operation is evaluated last.
Evaluation of a Second-Degree Polynomial
To develop a better understanding of the rules of operator precedence, consider the eval-
uation of an assignment expression that includes a second-degree polynomial ax 2 + bx + c :
y=a*x*x+b*x+c;
6
1
2
4
3
5
The multiplication operations are evaluated first in left-to-right order (i.e., they associate
from left to right), because they have higher precedence than addition. (Java has no arith-
metic operator for exponentiation, so x 2 is represented as x * x . Section 5.4 shows an al-
ternative for performing exponentiation.) The addition operations are evaluated next from
left to right . Suppose that a , b , c and x are initialized (given values) as follows: a=2 , b=3 ,
c=7 and x=5 . Figure 2.13 illustrates the order in which the operators are applied.
You can use redundant parentheses (unnecessary parentheses) to make an expression
clearer. For example, the preceding statement might be parenthesized as follows:
y = (a * x * x) + (b * x) + c;
 
Search WWH ::




Custom Search