i have been studying for Oracle java certification exam for a while.
today i came across a question asking which part of expression evaluates.
it was sth like a() || b() && c().
so far everything seems ok. && operator precedence has higher priority then || operator and it evaluates first and then || operator evaluates.
the problem arises when i try to run similar code on my windows 7/java 7 machine. when i run my code the || operator evalautes first. I checked a few books, and the one i study(manning java associate prep.) it says vice versa. what do you think whats wrong?
here is my code you can check
public class Dummy {
public static void main(String[] arg) {
boolean ax = method1() || method2() && method3() ;
}
public static boolean method1(){
System.err.println("method1");
return false;
}
public static boolean method2(){
System.err.println("method2");
return false;
}
public static boolean method3(){
System.err.println("method3");
return true;
}
}
Edit : what i get as output : method1 , method 2 What i expect : method2 , method1
edit 2: this is what the book says (manning OCA java Se 7 programmer 1 cert. guide) page 507
The expression (a >= 99 || a <= 33 && b == 10) has three operands together with the OR(||) and AND(&&) short-circuit operators.
Because the short-circuit operator AND has higher operator precedence than the short-circuit operator OR, the expression is evaluated as follows: (a >= 99 || (a <= 33 && b == 10)) Evaluation of the preceding expression starts with the evaluation of (a <= 33 && b == 10).
Because a <= 33 evaluates to true, the operator && evaluates the second operand (b == 10) to determine whether (a <= 33 && b == 10) will return trueor false. a <= 33returns true and b == 10 returns false, so the expression (a <= 33 && b == 10)returns false. The original expression—(a >= 99 || (a <= 33 && b == 10)) is now reduced to the following expression: (a >= 99 || false)
The short-circuit operator OR(||) executes its first operand (even if the value of the second operand is known), evaluating a >= 99. So for this expression, all three oper-ands are evaluated.....