23rd Apr 2024, 10:21 AM
Naing Ko
Naing Ko - avatar
4 odpowiedzi
+ 4
Naing Ko first, it is important to see past the non-standard indentation that makes it confusing to read. The line after the if statement should be indented like this: if (++n<4 && n++>10 & ++n==5 || ++n==10) System.out.println("pass"); System.out.println(n); In the conditional, we evaluate from left to right. The expression (++n<4) first increments n from 4 to 5, then it compares 5<4 and results in false. The next operator is &&. Java uses short circuit logic evaluation. Since the first operand was false, it does not matter whether the next operand is true or false. It skips the next operand as it is now moot. So it skips past all of (n++>10 & ++n==5). Next is Boolean operator ||, which has potential to change the conditional outcome, so it proceeds to evaluate the operand (++n==10). It increments n from 5 to 6, and then compares 6==10. The result is false. Since (false || false) evaluates to false, execution skips to the end of the if statement. The next line prints n, which is 6.
23rd Apr 2024, 10:26 PM
Brian
Brian - avatar
+ 2
I think the `n` variable starts at 4 and is incremented several times in a complex conditional statement in the `if` block. The `if` statement uses pre-increment operators (`++n`) that increase the value of `n` before evaluating each condition.
23rd Apr 2024, 11:34 AM
piano T
+ 2
Brian I didn't know Java use short circuit logic evaluation, and your explanation makes perfect sense to me.
24th Apr 2024, 7:57 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Logical operators && and || short-circuits. Bitwise operators & and | do not short-circuit. Also note that there is no operator overloading in Java. in C++ overloaded && or || loses the default short-circuit behavior. https://stackoverflow.com/questions/25913237/is-there-actually-a-reason-why-overloaded-and-dont-short-circuit#:~:text=The%20reason%20is%20that%20the,other%20built%2Din%20control%20flow.
24th Apr 2024, 11:02 AM
Bob_Li
Bob_Li - avatar