Java Reference
In-Depth Information
Parentheses for Grouping Subexpressions
Parentheses are used to group terms in Java expressions in the same manner as in algebraic
expressions. For example, to multiply a times the quantity b + c , we write
a * (b + c)
If an expression contains nested parentheses , such as
((a + b) * c)
the expression in the innermost set of parentheses ( a + b in this case) is evaluated first .
Rules of Operator Precedence
Java applies the operators in arithmetic expressions in a precise sequence determined by the
rules of operator precedence , which are generally the same as those followed in algebra:
1. Multiplication, division and remainder operations are applied first. If an expres-
sion contains several such operations, they're applied from left to right. Multipli-
cation, division and remainder operators have the same level of precedence.
2. Addition and subtraction operations are applied next. If an expression contains
several such operations, the operators are applied from left to right. Addition and
subtraction operators have the same level of precedence.
These rules enable Java to apply operators in the correct order . 1 When we say that
operators are applied from left to right, we're referring to their associativity . Some opera-
tors associate from right to left. Figure 2.12 summarizes these rules of operator precedence.
A complete precedence chart is included in Appendix A.
Operator(s)
Operation(s)
Order of evaluation (precedence)
*
/
%
Multiplication
Division
Remainder
Evaluated first. If there are several operators of this
type, they're evaluated from left to right .
+
-
Addition
Subtraction
Evaluated next. If there are several operators of this
type, they're evaluated from left to right .
=
Assignment
Evaluated last.
Fig. 2.12 | Precedence of arithmetic operators.
Sample Algebraic and Java Expressions
Now let's consider several expressions in light of the rules of operator precedence. Each
example lists an algebraic expression and its Java equivalent. The following is an example
of an arithmetic mean (average) of five terms:
1.
We use simple examples to explain the order of evaluation of expressions. Subtle issues occur in the
more complex expressions you'll encounter later in the topic. For more information on order of eval-
uation, see Chapter 15 of The Java™ Language Specification ( http://docs.oracle.com/javase/
specs/jls/se7/html/index.html ).
 
 
Search WWH ::




Custom Search