&-逻辑与 |-逻辑或 !-逻辑非 &&-短路与 ||-短路或 ^-逻辑异或
a | b | a&b | a|b | !a | a^b | a&&b | a||b |
---|---|---|---|---|---|---|---|
T | T | T | T | N | N | T | T |
T | N | N | T | N | T | N | T |
N | T | N | T | T | T | N | T |
N | N | N | N | T | N | N | N |
逻辑运算符需要注意的几点:
public class Test{
public static void main(String[] args) {
int a = 1;
int b = 2;
if (a == b && test()){
System.out.println("world");
}
}
public static boolean test() {
System.out.println("hello");
return false;
}
}
由于a==b为假,所以右边不参与计算,最后什么都不会输出。
public class Test{
public static void main(String[] args) {
int a = 1;
int b = 2;
if (a < b && test()){
System.out.println("world");
}
}
public static boolean test() {
System.out.println("hello");
return false;
}
}
由于a<b为真,此时右边参与运算,但是右边结果为false,所以整个判断表达式为false,即不会运行到if里面,所以会输出只会hello。
public class Test{
public static void main(String[] args) {
int a = 1;
int b = 2;
if (a == b && test()){
System.out.println("world");
}
}
public static boolean test() {
System.out.println("hello");
return false;
}
}
由于a<b为真,此时右边参与运算,右边结果也为true,所以整个判断表达式为true,会运行到if里面,所以会输出只会hello wrold。