首页 > 解决方案 > sequence of actions in the logical expression

问题描述

I want to ask about correct sequence "reading" of this logical expression:

(true && false | true) 

I thought it returns false, because of first expression - true && false But probably I'm doing something wrong and it's should be "reading" another way. Can you explain what's correct way to reading it?

标签: javalogical-operators

解决方案


Check the following table of Operators Precedence.

| (bitwise inclusive OR) has higher precedence than && (logical AND), so false | true is evaluated first.

That said, the evaluation order doesn't matter in your example. Both (true && false) | true and true && (false | true) return true. In the first case it's false | true), which is true. In the second case it's true && true, which is also true.

Now, here's an example where the operator precedence makes a difference:

System.out.println (false && true | true);
System.out.println (false && true || true);

| has a higher precedence than &&, but && has a higher precedence than ||.

Therefore these expressions are evaluated as:

System.out.println (false && (true | true));
System.out.println ((false && true) || true);

As a result, the first returns false and the second returns true.


推荐阅读