HOWTO · Java

在 Java 中使用 AND 和 OR 運算子

使用 Java 的 && 和 || 組合布林條件,理解短路求值,並避免與 & 和 | 混淆。

本頁內容

所有條件都必須為真時使用 &&,只要一個條件為真時使用 ||。兩者都會進行短路求值:只有右側仍可能改變結果時,Java 才會計算右側。因此 text != null && !text.isEmpty()textnull 時不會呼叫 isEmpty()

! 會反轉布林條件。Java 要求 booleanBoolean,不會將數字或非空字串自動轉為真值。Java Language Specification 定義了這些規則。

選擇 &&||!

只有兩個運算元都為真時 && 才為真;任一個為真時 || 為真。以下程式已在 Polyglot 的 OpenJDK 11.0.32 中編譯並執行。

public class LogicalOperators {
    public static void main(String[] args) {
        boolean hasTicket = true;
        boolean isMember = false;

        System.out.println("ticket && member: " + (hasTicket && isMember));
        System.out.println("ticket || member: " + (hasTicket || isMember));
        System.out.println("!member: " + !isMember);

        int age = 20;
        boolean canEnter = age >= 18 && age <= 65;
        System.out.println("can enter: " + canEnter);
    }
}
ticket && member: false
ticket || member: true
!member: true
can enter: true

先檢查 null

public class ShortCircuitBoundary {
    public static void main(String[] args) {
        String text = null;

        boolean safe = text != null && !text.isEmpty();
        System.out.println("&& with null: " + safe);

        try {
            boolean unsafe = text != null & !text.isEmpty();
            System.out.println("& with null: " + unsafe);
        } catch (NullPointerException exception) {
            System.out.println("& with null: NullPointerException");
        }
    }
}
&& with null: false
& with null: NullPointerException

使用 && 時,左側為 false 已可決定結果,因此不會解參考右側。& 會計算兩側,所以這裡會產生顯示的例外。 Scanner.nextLine() 不會回傳 null;這個保護模式適用於可能為 null 的回傳值、設定或欄位。

短路求值無法保護的情況

只有左側已可決定結果時,短路求值才跳過右側。Boolean enabled = null 需要 enabled != null && enabledenabled && otherCondition 在拆箱時可能擲出 NullPointerException。不要將必須執行的工作放在可能被跳過的一側。

不要以 & 取代 &&

&| 可用於 boolean,但總會計算兩側;對整數它們也是位元運算子。一般保護條件應使用 &&||,不要在條件中放入 index++ 這類可能被短路跳過的副作用。