重複の可能性:
& と && の違い
Javaでの短絡操作に関するいくつかのチュートリアルと回答を読みましたが、Javaが二重垂直パイプと二重アンパサンドの短絡を処理する方法の違いをまだよく理解していません。例えば ...
論理 AND 短絡評価が失敗するのはなぜですか?
JSL 15.23 を引用します。条件付き And 演算子 &&
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is 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 );
}
}