Java 三元運算子


三元運算子使用 3 個運算元,可以用它來替換 if else 語句。這可以使程式碼更簡單、更緊湊。

三元運算子的語法如下 −

Expression ? Statement 1 : Statement 2

在上述語法中,表示式是一個條件表示式,結果為 true 或 false。如果表示式的值為 true,則執行語句 1,否則執行語句 2。

以下是一個在 Java 中演示三元運算子的程式。

示例

 線上演示

public class Example {
   public static void main(String[] args) {
      Double num = -10.2;
      String str;
      str = (num > 0.0) ? "positive" : "negative or zero";
      System.out.println("The number " + num + " is " + str);
      }
}

輸出

The number -10.2 is negative or zero

現在讓我們瞭解上述程式。

定義了數字 num。然後使用三元運算子。如果 num 大於 0,則 str 儲存 "positive",否則儲存 "negative or zero"。然後針對指定數字顯示這條資訊。演示了此程式碼片段如下。

Double num = -10.2;
String str;
str = (num > 0.0) ? "positive" : "negative or zero";
System.out.println("The number " + num + " is " + str);

更新於: 25-6 月 2020

2K+ 已檢視

職業生涯開始啟動

完成課程獲得認證

開始
廣告