The else if Statements


The else if Statements

🙋 Need help? Ask an expert now!

The else if statement takes the if statement functionality one step further. Instead of having two outcomes, the programmer can create as many outcomes as they like, each one with its own expression. Take a look at the use of the else if statement below.
package exlcode;

public class ElseIfStatementExample {

  public static int exampleVariableOne = 37;

  public static void main(String[] args) {
    // else if statements have to include boolean expressions
    if (exampleVariableOne < 10 /* expression */) {
      System.out.println("The number is smaller than 10");
    } else if (exampleVariableOne < 20 /* expression */) {
      System.out.println("The number is between 10 and 20");
    } else if (exampleVariableOne < 30 /* expression */) {
      System.out.println("The number is between 20 and 30");
    } else {
      System.out.println("The number is larger than 30");

Each else if statement has its own expression that returns true or false. Only the FIRST expression that evaluates to "true" is executed. As we see above, if the expression exampleVariableOne &lt; 10 returns a value of "true", only the statements within the curly brackets of the if statement are executed, and all the statements that follow are ignored. If none of the expressions evaluate to "true", the statement inside the curly braces of the else statement are executed. Remember these vital rules when working with if statements:

  1. The if statement may contain zero or one else statement that must come after any else if expressions.
  2. The if statement may have zero or more else if expressions that must come before the else statement.
  3. Once the expression in an else if statement evaluates to true, all the remaining else if and else expressions are ignored.

Application Question