I have a doubt related to precedence order in the following code snippet.
public class PrecedenceTrial { public static void main(String...args) {
if(fun1() && fun2() | fun3()) { System.out.println("inside if block"); }
}
public static boolean fun1() { System.out.println("inside fun 1"); return true; }
public static boolean fun2() { System.out.println("inside fun 2"); return true; }
public static boolean fun3() { System.out.println("inside fun 3"); return false; }
}
when i am executing the program i get
inside fun 1 inside fun 2 inside fun 3 inside if block but i am not able justify this As | (Bitwise OR operator) is having higher precedence than && (logical AND operator) So, fun2() should be associated with | operator and fun2() and fun3() should be evaluated first as they are operands for | operator and && should be evaluated afterwards. but i am not getting the result as per to my view.
Please clarify it and correct me wherever i am wrong.
what you are saying is correct. '|' has higher precedence then '&&' and Associativity is left to right. That means the expression left to | will evaluate first.
In this example "if(fun1() && fun2() | fun3())" expression "fun1() && fun2()" is left to that | so it will evaluates first then fun3(). To evaluate this "fun1() && fun2()" first it will execute fun1(),if its true then it will execute fun2()
i hope this will clear your doubt [ July 16, 2008: Message edited by: winay Kumar ]
Now i understood that evaluation must happen before applying precedence rules and in exceptional cases like operators && || and ?: ,right side operands can be skipped for evaluation due to short circuit behaviour.
Regards
Jolly
We're all out of roofs. But we still have tiny ads: