note
note copied to clipboard
Java boolean 运算符 && || & |
看一下,以下代码会输出什么?
public static void main(String[] args) {
boolean t1 = true;
boolean t2 = true;
boolean f1 = false;
boolean f2 = false;
// 前面是||
System.out.println(t1 || f1 && f2);
System.out.println((t1 || f1) && f2);
System.out.println(t1 | f1 & f2);
System.out.println((t1 | f1) & f2);
// 前面是&&
System.out.println(t1 && f1 || t2);
System.out.println(t1 && (f1 || t2));
System.out.println(t1 & f1 | t2);
System.out.println(t1 & (f1 | t2));
}
还记得有过这样的说法吗?
1、当 ||
时,只要前面的结果为true时,后面无论怎么都是true,
2、当 &&
时,只要前面的结果为false,2后面的结果无论怎样都是false。
正确结果如下:你的答案是对的嘛:
true
false
true
false
true
true
true
true
很显然,说法1是正确的,但是说法2是错误的。
原因很简单,这个只是一个结论,而真正的计算方式应该考虑优先级。&&
的运算符优先级比 ||
高。说法1、2都只是根据优先级来推论出来的,JVM会对指定的运算进行优化。
至于 &&
,&
,||
,|
的区别,看下面的说明吧:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
short-circuiting
直译是短路的意思,具体为什么不安全,现在我也不太清楚。看到了可以讨论下。