File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Precedence rules in a java expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Precedence rules in a java expression" Watch "Precedence rules in a java expression" New topic

Precedence rules in a java expression

Karim Kiswarday
Ranch Hand

Joined: Oct 01, 2010
Posts: 50

Hello ranchers, I have a little doubt about the precedence in a java expression.

When I use the short-circuit logical operator (&& and ||) the evaluation finish when a false (for the && operator) or true (||) value is found in the expression (with the rest of operations not evaluated), but I know also that logical operators (& and |) have an bigger priority respect to them.

Whether I have the below expression and I don't use the parenthesis, the evalutation is calculated from left to right and not for precedence.

My problem is not about the result, but it is concern that --y and ++x are not execute.
When the precedence is used?
And when the left to right rule is used?


No fun at the table, no fun in the sack.
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 209

Hello Karim......
You probably be knowing what's the use of Short || as you can see that when the 1st condition satisfies i.e True it does not check the other expression.Hence the --y and ++ x wont execute as you said..........

and yeah even i was confused that does it always follows left to right rule. And yeah It Does Follows...i have experimented many times and in many combination's and it always follows left to right rule .....So for eg if(condition1 || condition2 |condition 3).....consider condition1 is false so now it checks whether condition2 is true and if it's true then it wont execute condtion 3.......

Hope it Helps


dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Hi Karim,

You are correct that ++ and -- generally have higher precedence. If we test a simple comparison condition, we see this clearly:

y :6
x :2

The increment operators were evaluated before the comparisons.
BUT the condition of an IF statement is evaluated left to right. So when we have a compound condition:

conditions met
x :4
y :4

To the left of the || operator, we see that the increment and decrement have been evaluated before the == test, as expected.
But think of the code to the right of the || operator as a self-contained statement whose evaluation happens totally independently.
This is why short-circuit operators are so useful. Not only is the result of the second comparison disregarded: it is never evaluated,
which means the second ++x is never reached.
I agree. Here's the link:
subject: Precedence rules in a java expression
jQuery in Action, 3rd edition