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
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Short circuit operator problem

Ranch Hand
Posts: 35
• Number of slices to send:
Optional 'thank-you' note:
Hi All,

I have the following two code snippet.

A)
B)

A gives 'Value of i : 1'
B gives 'Value of i : 2'
For A the first condition before || evaluates to true and hence short circuits the whole expression. But the short circuit does not happen for B where first condition before && evaluates to false. Please explain.

Amit
[ December 26, 2007: Message edited by: Amit Ghai ]

Ranch Hand
Posts: 52
• Number of slices to send:
Optional 'thank-you' note:
This is how it calculates
A) int i = 0;
if((++i > 0) || (++i > 1 && ++i > 5))
{}
System.out.println("Value of i : " + i);
and so the val of i becomes 1 now coming to B)

B)
int i = 0;
if((++i > 4 && ++i > 1) || (++i > 5))
{}
System.out.println("Value of i : " + i);
and so since in first condition (++i > 4 && ++i > 1) the first part returns false which makes the whole condition to return false and now since you have an || it evaluates the 2nd condition after the || which is ++i>5. So the value of i is evaluated twice and so the result 2. I hope you understood

Amit Ghai
Ranch Hand
Posts: 35
• Number of slices to send:
Optional 'thank-you' note:

I missed the point on operator precedence. This SCJP preparation is killing me

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html