Java位运算符和逻辑运算符
1. 简介
在 Java 中,我们有两种表示“与”的方式。但是使用哪个?
在本教程中,我们将研究 & 和 && 之间的区别。而且,我们将一路学习按位运算和短路。
2. 按位与的使用
按位与 (&) 运算符比较两个整数的每个二进制数字,如果两者都是 1,则返回 1,否则返回 0。
让我们看一下两个整数:
int six = 6;
int five = 5;
接下来,让我们对这些数字应用按位 AND 运算符:
int resultShouldBeFour = six & five;
assertEquals(4, resultShouldBeFour);
为了理解这个操作,让我们看一下每个数字的二进制表示:
Binary of decimal 4: 0100
Binary of decimal 5: 0101
Binary of decimal 6: 0110
& 运算符对每一位执行逻辑与,并返回一个新的二进制数:
0110
## 0101
0100
最后,我们的结果 - *0100 -*可以转换回十进制数 - 4。
让我们看看测试Java代码:
int six = 6;
int five = 5;
int resultShouldBeFour = six & five;
assertEquals(4, resultShouldBeFour);
2.1. 与布尔值一起使用 &
此外,我们可以将按位与 ( & ) 运算符与boolean操作数一起使用。仅当两个操作数都为true时才返回true,否则返回false。
让我们取三个boolean变量:
boolean trueBool = true;
boolean anotherTrueBool = true;
boolean falseBool = false;
接下来,让我们对变量trueBool 和anotherTrueBool应用按位与运算符:
boolean trueANDtrue = trueBool & anotherTrueBool;
然后,结果将是true。 接下来,让我们对trueBool和falseBool应用按位 AND 运算符:
boolean trueANDFalse = trueBool & falseBool;
在这种情况下,结果将为false。
让我们看看测试Java代码:
boolean trueBool = true;
boolean anotherTrueBool = true;
boolean falseBool = false;
boolean trueANDtrue= trueBool & anotherTrueBool;
boolean trueANDFalse = trueBool & falseBool;
assertTrue(trueANDtrue);
assertFalse(trueANDFalse);
3. 逻辑与的使用
与&类似,逻辑与 ( && ) 运算符比较两个布尔变量或表达式的值。**而且,仅当两个操作数都为true 时,它才会返回 true,否则返回false。
让我们取三个boolean变量:
boolean trueBool = true;
boolean anotherTrueBool = true;
boolean falseBool = false;
接下来,让我们对变量trueBool和anotherTrueBool应用逻辑 AND 运算符:
boolean trueANDtrue = trueBool && anotherTrueBool;
然后,结果将是true。 接下来,让我们对trueBool 和falseBool应用逻辑 AND 运算符:
boolean trueANDFalse = trueBool && falseBool;
在这种情况下,结果将为false。
让我们看看测试Java代码:
boolean trueBool = true;
boolean anotherTrueBool = true;
boolean falseBool = false;
boolean anotherFalseBool = false;
boolean trueANDtrue = trueBool && anotherTrueBool;
boolean trueANDFalse = trueBool && falseBool;
boolean falseANDFalse = falseBool && anotherFalseBool;
assertTrue(trueANDtrue);
assertFalse(trueANDFalse);
assertFalse(falseANDFalse);
3.1. 短路
那么,有什么区别呢?好吧,**&&运算符短路了。**这意味着当左侧操作数或表达式为false时,它不会计算右侧操作数或表达式。
让我们取两个表达式为假:
First Expression: 2<1
Second Expression: 4<5
当我们对表达式 2<1和4<5应用逻辑 AND 运算符时 ,它只计算第一个表达式2<1并返回false。
boolean shortCircuitResult = (2<1) && (4<5);
assertFalse(shortCircuitResult);
3.2. && 与整数一起使用
我们可以将 & 运算符与布尔或数字类型一起使用,但 && 只能与布尔操作数一起使用。将它与整数操作数一起使用会导致编译错误:
int five = 2;
int six = 4;
int result = five && six;
4.比较
- & 运算符总是计算两个表达式,而 && 运算符仅在第一个表达式为true时才计算第二个表达式
- & 按位比较每个操作数,而 && 仅对布尔值进行操作