• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Operator Presendence

 
Greenhorn
Posts: 25
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 3225
34
IntelliJ IDE Oracle Spring Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Let's go to the waterfront with this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic