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则不再对右侧语句