Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operator Presendence

 
ankit maini
Greenhorn
Posts: 25
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



According to the Operator Precedence < has higher precedence than || so it should solve first and output should be 4. but the answer is 3 WHY?
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
|| is a short circuit operator- Which means is the left hand side is already true, it will not go to the right hand side to evaluate.

So is &&. You can find related posts in the forum.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15282
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because of the operator precedence, line 2 is the same as this:

But the expression on the right side of the || will not be evaluated, exactly as Mohamed explained.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I understand it, precedence is not the same as order of evaluation.

Precedence dictates how "underparenthesized" expressions using different operators should be parenthesized. In other words, if an operand is between two different operators, then precedence dictates which operator "implies" parentheses.

In the expression...

...the precedence of < over || implies parentheses of...

...as opposed to...


But Java's order of evaluation dictates that the right operand of || will be evaluated only if the left side is false. (See JLS - 15.24 Conditional-Or Operator ||.)

Also see Precedence vs Associativity vs Order.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic