Java Reference
In-Depth Information
Operator hierarchy
Programminglanguageshavehierarchyrulesthatdeterminetheorderin
whicheachelementinanexpressionisevaluated.Forexample,theexpres-
sion
intvalue=8+4/2;
evaluatesto6becausetheJavaadditionoperatorhashigherprecedence
thanthemultiplicationoperator.Inthiscase,thecompilerfirstcalculates8
+4=12andthenperforms12/2=6.Ifthedivisionoperationwereper-
formedfirst,thenthevariablevalueevaluatesto10. Table8-5 liststhepre-
cedence of the Java operators.
Table 8-5
Precedence of Java Operators
OPERATOR
PRECEDENCE LEVELS
. [] ()
highest
+-~!++—
*/%
<> >>
<<=>>=>
== !=
&
^
|
&&
||
?:
=
lowest
Associativity rules
In some cases an expression can contain several operators with the same
precedence level. When operators have the same precedence, the order of
evaluationisdeterminedbytheassociativityrulesofthelanguage.Associa-
tivity can be left-to-right or right-to-left. In most programming languages,
including Java, the basic rule of associativity for arithmetic operators is
left-to-right. This is consistent with the way we read in English and the
Western European languages.
In Java, the left-to-right associativity rule applies to all binary opera-
tors. However, unary operators, as well as the assignment operator (=),
follow right-to-left associativity. Because of this variation in the associa-
tivity rules, you must exercise care in evaluating some expressions. Con-
sider the following case:
 
Search WWH ::




Custom Search