I'm not happy about this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22 . It clearly states the following:
"Each operator is commutative if the operand expressions have no side effects."
and
"These operators have different precedence, with & having the highest precedence and | the lowest precedence".
How come the JVM doesn't comply to it's own rules. Take for instance the following example.
public static void main(String[] args){
boolean bool = isTrue1() | isFalse1() & isFalse2() ;
System.out.println("Result : " + bool);
}
public static boolean isFalse1() {
System.out.println("1 : " + false);
return false ;
}
public static boolean isFalse2() {
System.out.println("2 : " + false);
return false ;
}
public static boolean isTrue1() {
System.out.println("3 : " + true);
return true ;
}
The result is:
3 : true
1 : false
2 : false
Result : true
While the actual result should be, according to the fact that & operators are evaluated before | operators:
1 : false
2 : false
3 : true
Result : true
Some explanation would be nice as to why this isn't correctly implemented. Even when adding parentheses around the second part, the correct precedence isn't used.
"These operators have different precedence, with & having the highest precedence and | the lowest precedence".
Just because they have higher precedence, doesn't mean their operands will be evaluated first.
This
boolean bool = isTrue1() | isFalse1() & isFalse2() ;
becomes equivalent to
boolean bool = isTrue1() | ( isFalse1() & isFalse2() ) ;
That's all precedence is.
As the Java Language Specification says, operator operands are evaluated left to right.
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With