通过一道笔试题来说明按位或|和逻辑或||,按位与&和逻辑与&&的区别
先上笔试题
Given the following code:
链接:https://www.nowcoder.com/questionTerminal/593cc3972afe4b32a49cd9c518571221
来源:牛客网
public class Test {
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);
}
}
What is the result?
- The program prints”0”
- The program prints”4”
- The program prints”8”
- The program prints”12”
- The code does not complete.
答案是第二个,
首先,逻辑与和逻辑或都属于逻辑运算符用于逻辑运算,按位与和按位或都属于按位运算符,可以作用于操作数的各个位(按位运算符可以应用于整数types:long,int,short,char,byte)
相同点是:对于两个逻辑量,两种运算符等效。
不同点是:逻辑与只判断两个均不为0吗,则为true(逻辑或只判断只要有一个不为0,则为true),但是按位与则将两个数转为二进制,对于每个位进行与运算,如果结果不为0,则为true(按位或,如果转化并运算的结果为0,则为false)。
且在判断两个逻辑量时也有所区别:逻辑运算符(&&和||)均具有短路特性,而按位运算符(&和|)不管两个逻辑怎样,这两个逻辑均会执行。
关于逻辑运算符(&&和||)均具有短路特性:
对于逻辑与&&:
表达式1&&表达式2,如果表达式1为假,表达式2就不会执行。
表达式1||表达式2,如果表达式1为真,表达式2就不会执行。
如题:
//i=0, i<10为true,但是依然执行methodB(4),之后 j=4
b = i < 10| methodB(4);
//i=0, i<10位true,可以决定结果,所以不会执行methodB(8),j依然=4
b = i < 10|| methodB(8);