aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes || operand Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "|| operand" Watch "|| operand" New topic
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: || operand
 
Similar Threads
Short-Circuit Logical Operators
operator
Doubt in K&B concerning topic :Operators
Strange IF condition
KB Question pg 314