可能重复:
& 和 && 的区别
我已经阅读了几篇关于Java中短路运算的教程和答案,但我仍然不太理解Java如何处理双竖线和双和号的短路。例如...
为什么逻辑 AND 短路评估失败?
引用JSL 15.23. 条件-与运算符 &&
条件-与运算符 && 类似于 & (§15.22.2),但仅在其左操作数的值为 true 时才计算其右操作数的值。
public static void main( String... args ) {
int a = 1;
int b = 2;
// Okay. Prints
if( a == 1 | b == 3 ) {
System.out.println( "Comparison via |" + "\na is " + a + "\nb is " + b );
}
// Okay. Prints
if( a == 1 || b == 3 ) {
System.out.println( "Comparison via ||" + "\na is " + a + "\nb is " + b );
}
// Okay. Does not print
if( a == 1 & b == 3 ) {
System.out.println( "Comparison via &" + "\na is " + a + "\nb is " + b );
}
// I don't understand. Shouldn't the Short Circuit succeed since the left side of the equation equals 1?
if( a == 1 && b == 3 ) {
System.out.println( "Comparison via &&" + "\na is " + a + "\nb is " + b );
}
}
|
和&
也是非短路逻辑或和与运算符。 - Steve Kuo