跳轉到內容

Java 程式設計/語句/if

來自華夏公益教科書,開放的書籍,開放的世界

if ... else 語句用於根據布林條件的結果有條件地執行兩個語句之一。

示例

if (list == null) {
  {{Java://|this block of statements executes if the condition is true
}
else {
  {{Java://|this block of statements executes if the condition is false
}

一個 if 語句有兩種形式

if (boolean-condition)
   statement1

if (boolean-condition)
   statement1
else
   statement2

如果要執行不同的語句,則使用第二種形式,如果布林條件為真或假。如果只想執行語句1,則使用第一個,如果條件為真,則不想執行備用語句,如果條件為假。

以下示例呼叫兩個 int 方法,f()f(),儲存結果,然後使用 if 語句測試 x 是否小於 y,如果是,則語句1主體將交換值。最終結果是 x 始終包含較大的結果,而 y 始終包含較小的結果。

int x = f();
int y = y();
if ( x < y ) {
  int z = x;
  x = y;
  y = z;
}
華夏公益教科書