+ 3

Why is the output 21? Its suppose to be 22... i guess

public class Program { public static void main(String[] args) { int x = 10, y = 10, z = 0; if (!(x++ > 10 && y++ > 10)) z = x + y; System.out.println(z); } }

16th Mar 2017, 9:52 AM
nabeer zahed chowdhury
nabeer zahed chowdhury - avatar
2 Answers
+ 16
When the first statement in a conditional statement containing && is evaluated to be false, the rest of the statement is automatically false. In (x++>10&&y++>10), only one was evaluated and hence either x or y was incremented by 1.
16th Mar 2017, 9:55 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
As a quick note, if you want both statements to run (even if the first statement guarantees the result of the boolean) use the binary operator (one '&' instead of two). So: int num = 4; if(false && ++num == 300) {} // first statement is false, so the second statement (where num is incremented) never runs. Can be replaced by: if(false & ++num == 300) {} // first statement is false, but the second statement runs anyways. In the first example, 'num' is never incremented (so it stays at 4). In the second example, num is incremented anyways (even though the boolean expression is guaranteed to return false), which increases 'num' to 5.
16th Mar 2017, 6:48 PM
Kevin