File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Precedence rules in a java expression

 
Karim Kiswarday
Ranch Hand
Posts: 50
Eclipse IDE Java PHP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks
KK
 
Sagar Shroff
Ranch Hand
Posts: 209
Java Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Karim......
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.......

Hope it Helps

Sagar
 
dennis deems
Ranch Hand
Posts: 808
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karim,

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

Output:
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:

Output:
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic