• 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
  • 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

|| 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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic