Java Reference
In-Depth Information
When incrementing or decrementing a variable in a statement by itself, the prefix
increment and postfix increment forms have the same effect, and the prefix decrement and
postfix decrement forms have the same effect. It's only when a variable appears in the con-
text of a larger expression that preincrementing and postincrementing the variable have
different effects (and similarly for predecrementing and postdecrementing).
Common Programming Error 4.8
Attempting to use the increment or decrement operator on an expression other than one to
which a value can be assigned is a syntax error. For example, writing ++(x + 1) is a syntax
error, because (x + 1) is not a variable.
Operator Precedence and Associativity
Figure 4.16 shows the precedence and associativity of the operators we've introduced.
They're shown from top to bottom in decreasing order of precedence. The second column
describes the associativity of the operators at each level of precedence. The conditional op-
erator ( ?: ); the unary operators increment ( ++ ), decrement ( -- ), plus ( + ) and minus ( - );
the cast operators and the assignment operators = , += , -= , *= , /= and %= associate from right
to left . All the other operators in the operator precedence chart in Fig. 4.16 associate from
left to right. The third column lists the type of each group of operators.
Good Programming Practice 4.5
Refer to the operator precedence and associativity chart (Appendix A) when writing ex-
pressions containing many operators. Confirm that the operators in the expression are per-
formed in the order you expect. If you're uncertain about the order of evaluation in a
complex expression, break the expression into smaller statements or use parentheses to force
the order of evaluation, exactly as you'd do in an algebraic expression. Be sure to observe
that some operators such as assignment ( = ) associate right to left rather than left to right.
Operators
Associativity
Type
++ --
right to left
unary postfix
++ -- + - ( type )
right to left
unary prefix
* / %
left to right
multiplicative
left to right
additive
+ -
< <= > >=
left to right
relational
== !=
left to right
equality
?:
right to left
conditional
= += -= *= /= %=
right to left
assignment
Fig. 4.16 | Precedence and associativity of the operators discussed so far.
4.14 Primitive Types
The table in Appendix D lists the eight primitive types in Java. Like its predecessor lan-
guages C and C++, Java requires all variables to have a type. For this reason, Java is referred
to as a strongly typed language .
 
 
Search WWH ::




Custom Search