Java Language If / Else If / Else Control

Download Java Language for free

Example

if (i < 2) {
  System.out.println("i is less than 2");
} else if (i > 2) {
  System.out.println("i is more than 2");
} else {
  System.out.println("i is not less than 2, and not more than 2");
}

The if block will only run when i is 1 or less.

The else if condition is checked only if all the conditions before it (in previous else if constructs, and the parent if constructs) have been tested to false. In this example, the else if condition will only be checked if i is greater than or equal to 2.

If its result is true, its block is run, and any else if and else constructs after it will be skipped.

If none of the if and else if conditions have been tested to true, the else block at the end will be run.

Nested break / continue