This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
You probably be knowing what's the use of Short ||.....so 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.......
You are correct that ++ and -- generally have higher precedence. If we test a simple comparison condition, we see this clearly:
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:
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.