I have come across following question from Dan's operator section tests: ________________________________________________________________________
What is the result of attempting to compile and run the above program? a. Prints: false,false,false b. Prints: false,false,true c. Prints: false,true,false d. Prints: false,true,true e. Prints: true,false,false f. Prints: true,false,true g. Prints: true,true,false h. Prints: true,true,true i. Runtime error j. Compiler error k. None of the above __________________________________________________________________________ Now, based on the operator precedence and operator evaluation rules, '&&' has got a higher precedence than '||'. So, according to me, these should be the order of steps executed at runtime:
b is assigned a true value
Since b is true, the short-circuit &&operator has to evaluate second operand, i.e. c
c is assigned a true value
The result of && operand is true
Now, the || operator is evaluated. a is assigned a true value.
Since a is already true, it returns the value of expression as true
Now, x is assigned a true value.
Based on this logic, the answer to this question should be 'h' while the correct answer is 'e'. (I have checked it with compiler too). Now, it looks like the operators are being evaluated from left to right but that should only occur when two operators are of equal precedence. Why is it behaving this way? If its always supposed to behave this way, what does the higher precedence of && to || imply? When does it usually come into action? Please support with an example. Thanks, Nidhi.
The evaluation order is like on a mathematical equation where x = a + b * c can be converted to x = a + (b * c) without actually altering the order of evaluation. The same is true here: boolean x = (a = true) || (b = true) && (c = true) equals boolean x = (a = true) || ((b = true) && (c = true))
I agree. In this question, JVM decides not to evaluate the logical AND part of expression because logical OR is happy with the left part already. You can even insert division by zero to the right part, it doesn't throw anything as long as the left part is true. [ September 24, 2003: Message edited by: Vad Fogel ]
posted 17 years ago
Thanks both of you! Its clear now. I did a little bit of experimenting to make the flow clear in my mind. For anybody who is interested, I am pasting the code and results below:
If you run this code, the results are as follows: i is4 i is6 i is2 true,true,false,16
Now, this makes it very clear. Once you resolve the precedence by putting brackets as suggested by Mika, the expression is evaluated from left-to-right. That's why, "i is4" is printed before "i is6" and "i is2". [ September 24, 2003: Message edited by: Nidhi Bangur ]
Your buns are mine! But you can have this tiny ad: