Answer the question
In order to leave comments, you need to log in
Is the order in which conditions are checked in a compound if-else conditional statement specified?
Let there be a compound conditional statement
if (A || B || C) {
...}
Is there a hardcoded sequence in which conditions A, B, C will be checked? Share the link, please, where to read in javadoc.
Answer the question
In order to leave comments, you need to log in
The conditional-or operator is syntactically left-associative (it groups left-to-right).
at run-time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subject to unboxing conversion (§5.1.8).
If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.
I don't know where to read about it in the javadoc, but the order is hard-coded: A is checked first, then B, then C.
And here's why it's done: if A is true, then there is no point in checking B and C.
Similarly for the condition (A && B && C): if A is false, then there is no point in checking B and C.
This is convenient, since you can write beautiful conditions. For example, if in the case (A || B || C) checking B under condition A will falsely result in an exception, then checking the condition (A || B || C) will not lead to an exception, due to the peculiarity that I described higher.
Left to right, as in any C-like language, unless some operator has higher precedence.
and of course if || then checks up to the first true, and if && then up to the first false
Depends on the compiler. In the good old Pascal, borland had a special key that set the so-called "full" condition checks, i.e. even if for the condition (A or B) A is true and in theory it is not necessary to calculate B, if the full calculations are explicitly indicated, B will also be calculated. I came across this because my programs crashed because of this, when I couldn’t calculate B with A == false (for example, division by 0).
The question is about Java, so it can't "depend on the compiler" in any way. Any "compiler" and jvm must work in the same way, as it is written in the specification, the link is given above. It is evaluated from left to right, for operators || and && incomplete condition checks. For operators & and | - full. There is nothing more to discuss here :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question