Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator precedence in Java

Tags:

java

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.

like image 799
user2890248 Avatar asked Dec 19 '22 18:12

user2890248


1 Answers

"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.

like image 137
Sotirios Delimanolis Avatar answered Dec 22 '22 08:12

Sotirios Delimanolis