+ 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); } }
2 Respostas
+ 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.
+ 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.