&&和||的短路逻辑是什么
java中的逻辑与(&&)和逻辑或(||)具有短路特性,即当表达式的结果已经确定时,将不再计算剩余部分。对于&&,如果左操作数为false,则整个表达式为false,跳过右操作数;对于||,如果左操作数为true,则整个表达式为true,跳过右操作数。

public class ShortCircuitDemo {
public static void main(String[] args) {
int a = 0;
// 逻辑与:左边为false,右边不执行
boolean result1 = (a != 0) && (1 / a == 1);
System.out.println("Result1: " + result1); // false
// 逻辑或:左边为true,右边不执行
int b = 1;
boolean result2 = (b != 0) || (1 / b == 1);
System.out.println("Result2: " + result2); // true
}
}上述代码展示了短路的基本行为。在result1的计算中,由于a != 0为false,右侧的1 / a不会执行,从而避免了除以零异常。而在result2中,左侧为true,右侧同样被跳过。
非短路运算符&和|的区别
非短路运算符&和|会计算所有操作数,无论左侧结果如何。这意味着即使左侧已经确定了最终结果,右侧的代码仍会被执行。这在需要确保副作用发生或进行位运算时非常有用。

立即学习“Java免费学习笔记(深入)”;
public class NonShortCircuitDemo {
public static void main(String[] args) {
int a = 0;
// 逻辑与:两边都执行,导致ArithmeticException
try {
boolean result = (a != 0) & (1 / a == 1);
} catch (ArithmeticException e) {
System.out.println("Caught exception in & operation");
}
// 逻辑或:两边都执行
int b = 1;
boolean result2 = (b != 0) | (1 / b == 1);
System.out.println("Result2: " + result2); // true
}
}在NonShortCircuitDemo中,使用&时,即使a != 0为false,右侧的1 / a仍然会被执行,导致运行时异常。而|运算符也会执行两侧,但在此例中未引发异常。
短路特性对程序性能和安全的影响
短路特性不仅影响程序的安全性(如避免空指针或除零异常),还影响性能。通过跳过不必要的计算,可以减少CPU周期消耗。此外,在条件判断中,短路允许开发者以简洁的方式处理复杂逻辑,例如检查对象是否为null后再访问其属性。
public class PerformanceAndSafetyDemo {
public static void main(String[] args) {
String str = null;
// 安全地检查字符串长度
if (str != null && str.length() > 5) {
System.out.println("String is long enough");
} else {
System.out.println("String is null or too short");
}
}
}在PerformanceAndSafetyDemo中,str != null先于str.length() > 5评估。如果str为null,右侧不会被执行,从而防止了NullPointerException。这种模式在防御性编程中至关重要。


















