Boolean Operator Priority in Java

I am not happy with 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 priorities, with the highest priority and the lowest priority."

Why the JVM does not comply with its own rules. Take, for example, 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 ;
}

Result:

3 : true
1 : false
2 : false
Result : true

While the actual result should be in accordance with the fact that the operators are evaluated to | operators:

1 : false
2 : false
3 : true
Result : true

Some explanation would be nice why this is not implemented correctly. Even when adding parentheses around the second part, the correct priority is not used.

+3
5

" , | ".

, , , .

boolean bool = isTrue1() | isFalse1() & isFalse2() ;

boolean bool = isTrue1() | ( isFalse1() & isFalse2() ) ;

.

Java, .

Java , , -, , .

+7

, | , :

boolean bool = isTrue1() | isFalse1() & isFalse2()

:

  boolean bool = (isTrue1()) | (isFalse1() & isFalse2())

, | . , java .

isTrue1(), , paranthesis, , : isFalse1(), isFalse2().

+2

; , , . ​​

+1

, , . Java , .

If you really use logical operations (replace | with || and and with & &), the result will look like this:

1 : true
Result : true
0
source

Java will call all functions before comparing the results, because instead of logical comparators (& & and ||) you use binary comparators (& and |)

-2
source

All Articles