Java Programming/Statements/if

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The if ... else statement is used to conditionally execute one of two statements, depending on the result of a boolean condition.

Example:

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
}

An if statement has two forms:

if (boolean-condition)
   statement1

and

if (boolean-condition)
   statement1
else
   statement2

Use the second form if you have different statements to execute if the boolean-condition is true or if it is false. Use the first if you only wish to execute statement1 if the condition is true and you do not wish to execute alternate statements if the condition is false.

The following example calls two int methods, f() and f(), stores the results, then uses an if statement to test if x is less than y and if it is, the statement1 body will swap the values. The end result is x always contains the larger result and y always contains the smaller result.

int x = f();
int y = y();
if ( x < y ) {
  int z = x;
  x = y;
  y = z;
}