| Author |
|| operand
|
Netty poestel
Ranch Hand
Joined: Sep 20, 2004
Posts: 131
|
|
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
|
 |
David Ulicny
Ranch Hand
Joined: Aug 04, 2004
Posts: 724
|
|
++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
|
SCJP<br />SCWCD <br />ICSD(286)<br />MCP 70-216
|
 |
Netty poestel
Ranch Hand
Joined: Sep 20, 2004
Posts: 131
|
|
|
 |
Anil Kumar Saha
Ranch Hand
Joined: Apr 07, 2004
Posts: 111
|
|
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
|
Regards,
Anil Kumar Saha
SCJP 1.4
http://www.agilej.blogspot.com/
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
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 ]
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
 |
|
|
subject: || operand
|
|
|