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) statement1elsestatement2
如果要執行不同的語句,則使用第二種形式,如果布林條件為真或假。如果只想執行語句1,則使用第一個,如果條件為真,則不想執行備用語句,如果條件為假。
以下示例呼叫兩個 int 方法,f() 和 f(),儲存結果,然後使用 if 語句測試 x 是否小於 y,如果是,則語句1主體將交換值。最終結果是 x 始終包含較大的結果,而 y 始終包含較小的結果。
intx = f();inty = y();if( x < y ) {intz = x; x = y; y = z; }