您的位置:首页 > 编程语言 > Java开发

Java中运算符“|”和“||”以及“&”和“&&”区别

2018-10-10 15:19 225 查看

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: