Win a copy of Spring Boot in Practice this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

|| operand

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test {
public static void main(String [] args) {
int x= 0;
int y= 0;
for (int z = 0; z < 1; z++) {
if (( ++x > 2 ) || (++y > 2)) {
x++;
}
}
System.out.println(x + " " + y);
}
}

++x = 1 and 1 > 2 returns false, so it moves to the 2nd operand
++y= 1 and 1>2 is false.
so the x++ should not get executed.

can anyone clarify the output 1 1.
TIA
 
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


++x = 1 and 1 > 2 returns false, so it moves to the 2nd operand
++y= 1 and 1>2 is false.



you answered yourself, ++x and ++y, so after this operation is x = 1 and y = 1
 
Netty poestel
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

The for()loop iterates for 1 time only.Then control goes to if() loop. Now
(( ++x > 2 ) results false.Since || is a short circuit operator, it should not check (( ++y > 2 ), so the value of y should remain 0.

But the output 1,1.

Please clear my doubts
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Now (( ++x > 2 ) results false.Since || is a short circuit operator, it should not check (( ++y > 2 ),


|| is the logical OR operator, so it must check the second operand if the first operand is false. || shortcuts only if the first operand is true.


Similarly && is the logical AND operator, it shortcuts only if the first operand is false.
[ October 08, 2004: Message edited by: Barry Gaunt ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic