1.“|”运算符:不论运算符左侧为true还是false,右侧语句都会进行判断,下面代码
public class TestOperator {
private static int j = 0;
private static Boolean methodB(int k) {
j += k;
return true;
}
public static void methodA(int i) {
boolean b;
b = i < 10 | methodB(4);
}
public static void main(String args[]) {
methodA(0);
System.out.println(j);
}
}
打印结果:4
2.“||”运算符:若运算符左边为true,则不再对运算符右侧进行运算,如下代码:
public class TestOperator {
private static int j = 0;
private static Boolean methodB(int k) {
j += k;
return true;
}
public static void methodA(int i) {
boolean b;
b = i < 10 | methodB(4);
b = i < 10 || methodB(8);
}
public static void main(String args[]) {
methodA(0);
System.out.println(j);
}
}
打印结果:4,说明“||”运算,左边为true后就不会再执行右边,而“|”运算,左边为true后依然会执行右边。
3.&运算符与|运算符类似:不论运算符左侧为true还是false,右侧语句都会进行判断:
public class TestOperator {
private static int j = 0;
private static Boolean methodB(int k) {
j += k;
return true;
}
public static void methodA(int i) {
boolean b;
b = i > 10 & methodB(4);
}
public static void main(String args[]) {
methodA(0);
System.out.println(j);
}
}
打印结果:4,说明&运算符左侧为false,单依然会运行右侧语句。
4.“&&”运算符与“||”运算符类似:若运算符左侧为false则不再对右侧语句进行判断:
public class TestOperator {
private static int j = 0;
private static Boolean methodB(int k) {
j += k;
return true;
}
public static void methodA(int i) {
boolean b;
b = i > 10 & methodB(4);
b = i > 10 && methodB(8);
}
public static void main(String args[]) {
methodA(0);
System.out.println(j);
}
}
打印结果:4,说明&&运算符左侧为false则不再对右侧语句
Java逻辑运算符详解
本文详细解析了Java中逻辑运算符“|”、“||”、“&”和“&&”的区别与应用。通过具体代码示例,阐述了短路运算符与非短路运算符在条件判断中的行为差异,以及它们如何影响程序的执行效率。
904

被折叠的 条评论
为什么被折叠?



