Operator Precedence

By: aathishankaran Printer Friendly Format    

Operator Precedence

 

            Table shows the order of precedence for java operators, from highest to lowest. Notice that the first row shows items that you may not normally think of as operators: parentheses, square brackets, and the dot operator. Parentheses are used to alter the precedence of an operation. As you know from the previous articles, the square brackets provide array indexing. The dot operator is used to dereference objects and will be discussed later.

 

Highest

 

 

 

( )

[]

.

 

++

--

~

!

*

/

%

 

+

-

 

 

>>

>>>

<<

 

>

>=

<

<=

==

!=

 

 

&

 

 

 

^

 

 

 

|

 

 

 

&&

 

 

 

||

 

 

 

?:

 

 

 

=

op=

 

 

Lowest

 

 

 

 

 

Using Parentheses

 

            Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result you desire. For example, consider the following expression:

 

           a >> b + 3

 

            This expression first adds 3 to band then shifts a right by that result. That is, this expression can be rewritten using redundant parentheses like this:

 

       a >> (b + 3)

 

            However, if you want to first shift a right by b positions and then add 3 to that result, you will need to parenthesize the expression like this:

 

            ( a >> b) + 3

 

            in addition to altering the normal precedence of an operator, parentheses can sometimes be used to help clarify the meaning of an expression. For anyone reading your code, a complicated expression can be difficult to understand. Adding redundant but clarifying parentheses to complex expressions can help prevent confusion later. For example, which of the following expressions is easier to read?

 

            a | 4 + c >> b & 7

    (a | (((4 + c) >> b) & 7))

 

            One another point: parentheses (redundant or not) do not degrade the performance of your program. Therefore, adding parentheses to reduce ambiguity does not negatively affect your program.





Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial