Else if statement in Java: complement the if statement and the else statement


Keywords: else if statement, else statement, if statement, conditional statements, boolean, flowchart

Else if statement Java

The third article in the chapter on conditional statements will introduce the else if statement that allows us to specify a new condition when the first condition is false.

What is the else if statement in Java?

As the name suggests, the else if statement is closely linked to the if statement and the else statement that we saw in the previous articles. Simply put, it could describe it as the else if statement being used as an additional if statement in the program. Additionally, the else if statement is sometimes referred to as “if..else…if ladder”.

In short, the else if statement in Java

  • A conditional statement that determines the actions the program should execute based on a logical condition
  • Similar to the if statement has a logical condition that is true or false
  • Must be used in conjunction with an if statement

How else if statement in java works?

An else if statement in Java could be described as an extension of the if statement, or that we can use another if statement after the first one. Simply put, an else if statement helps to solve problems when you want to execute different operations depending on the results of several different conditions. However, note that the if statement has a higher priority than the else if statement. Meaning, if the condition of the if statement is true, the program will ignore both the else if and the else statement.

Key points to highlight:

  • It’s possible to use several else if statements consecutive.
  • If the logical statement of the if statement is true, the else if statement (s) will not be executed.
  • There must be an else statement if an else if statement has been declared so the program can proceed when none of the if, and else if, conditions are true.

Let’s illustrate the else if statement

Else if statement Java

Figur 1: Else if statement in Java

What we are seeing is that:

  • When the condition of the if statement is true, the if statement code block is executed and the program then proceeds without testing the remaining conditions
  • However, when the if statements condition is false, the program goes on to check the else if statement’s condition.
  • The program continues until it comes to the condition that is true. If no condition is true, the else statement is executed.

How to create else statement in Java?

The else if statement uses similar syntax as the if statement

  • Use the reserved word else if followed by the logical condition you want to evaluate inside the parentheses ( )
  • The logical condition evaluates a true or false statement
  • Enclose the code block with curly brackets { }

Pay attention to; you can only create an else if statement in conjunction with an if statement and must have a subsequent else statement.

Syntax: Declare else if statement in Java

The syntax of an else if statement looks as follows.  

if (logical expression) {
         
      // if statements code block
}

else if (logical expression) {
         
      // else if statements code block
}

else {
         
      // else statements code block 
}

Examples: Else if statement in Java

Let’s solve a few examples of how to use an else if statement in Java. We will start with a straightforward example and then end with two more extended examples where we will program a discount system for a store and a program that compares random numbers.

Example 1: Create else if statement

Similar to the example we had for the else statement, let’s show a short and simple example that demonstrates how an else if statement complements the if statement and the else statement.

public class Example{
   public static void main(String[] args) {
   
      int number = 8; 

      if (number > 10) {
         System.out.println("This is the IF statement"); 
      } 

      else if (number > 5) {
         System.out.println("This is the ELSE IF statement");
      }

      else {
         System.out.println("This is the ELSE IF statement");
      }
   }
} 

We then get the result

This is the ELSE IF statement

However, let’s change the condition of the if statement to demonstrate that the if statement has a higher priority than the else if statement.

public class Example{
   public static void main(String[] args) {
   
      int number = 8; 

      if (number > 3) {
         System.out.println("This is the IF statement"); 
      } 

      else if (number > 5) {
         System.out.println("This is the ELSE IF statement");
      }

      else {
         System.out.println("This is the ELSE IF statement");
      }
   }
} 

To conclude, in the example above, both the conditions of the if statement and the else if statement are true. But since the conditions of the if statement fulfilled, the else if statement’s conditions will not be evaluated. The program ignores the else if statement and the else statement and continues in the program. Thus, we get the result

This is the IF statement

Example 2: Discount system by using several else if statements

We will now help a store by coding a system that will help them calculate how much discount the customers get on their purchase. The store has the following discount system if the total purchase is greater than:

  • 5% if the purchase exceeds 50 USD
  • 10% if the purchase exceeds 100 USD
  • 15% if the purchase exceeds 150 USD
  • 20% if the purchase exceeds 200 USD

Let’s code a program that displays how much discount the customer should receive and their price.

public class Example{
   public static void main(String[] args) {

      // The cost for the purchase is set to 1200
      int cost = 1200;
                                
      if(cost >= 2000){                              
         System.out.println("The discount is 20%");     
         System.out.println("Customers price: " + cost * 0.8);  
      }
      
      else if(cost >= 1500){                          
         System.out.println("The discount is 15%");
         System.out.println("Customers price: " + cost * 0.85);        
      }

      else if(cost >= 1000){                          
         System.out.println("The discount is 10%"); 
         System.out.println("Customers price: " + cost * 0.9);      
      }

      else if(cost >= 500){                           
         System.out.println("The discount is 5%");
         System.out.println("Customers price: " + cost * 0.95); 
      }

      else {                                            
         System.out.println("No discount");
         System.out.println("Customers price: " + cost);        
      }
   }
}

The result in this case will be

The discount is 10%
Customers price: 1080.0

Example 3: Else if statement that evaluates random numbers

In this example, we will use the built-in random class to generate random numbers. If you don’t remember how to use the random class to create random numbers in Java, you can read more about it here.

We want our program to:

  • Create three variables that are assigned a random integer value between 0 and 4.
  • If all variables have equal values, print the text “All three variables are equal”.
  • Moreover, if not all the variables are equal to each other, the program should compare whether two of the variables are equal to each other and in that case print which ones.
  • Finally, if none of the variables is equal to any other then the program should acknowledge that.
/// Imports the random class
import java.util.Random;

public class exempel {
        public static void main(String[] args) {

            // Creates an instance of the class random
            Random rand = new Random();

            // Three random integers
            int randomNumA = rand.nextInt(5);
            int randomNumB = rand.nextInt(5);
            int randomNumC = rand.nextInt(5);

            // Prints the value of the variables to 
            // make sure that it's correct
            System.out.println("The value of variable A is: " + randomNumA);
            System.out.println("The value of variable B is: " + randomNumB);
            System.out.println("The value of variable C is: " + randomNumC);
            
            // Checks if all variables are equal
            if (randomNumA == randomNumB && randomNumA == randomNumC) {
                System.out.println("All three variables are equal");
            }

            // If variable A is equal to variable B
            else if (randomNumA == randomNumB) {
                System.out.println("Variable A is equal to Variable B");
            }
            
            // If variable A is equal to variable C
            else if(randomNumA == randomNumC) {
                System.out.println("Variable A is equal to Variable C");
            }

            // If variable A is equal to variable C
            else if(randomNumB == randomNumC) {
                System.out.println("Variable B is equal to Variable C");
            }

            // If none of the variables are equal to each other
            else {
                System.out.println("None of the variables are the equal");
            }
        }
}

To conclude, it will be tricky to display what the answer will be because we get different answers every time. But copy the code and test it yourself.

Summary: Else if statement in Java  

The else if statement is used in conjunction with the if statement and the else statement. An else if statement is used to test additional conditions, and if true, execute a specified code block. Moreover, the else if statement must be used in conjunction with an if statement and also have a subsequent else statement. If the if statements condition is true, the else if statement conditions will not be evaluated, as it has a lower priority.

Furthermore, the else if statement is declared with the reserved words else if followed by a logical expression in parentheses ( ). The logical expression evaluates a condition that is either true or false. The code block to be executed if the condition is true is written inside the curly brackets {}.

Syntax: Declare else if statement in Java

if (logical expression) {
         
      // if statements code block
}

else if (logical expression) {
         
      // else if statements code block
}

else {
         
      // else statements code block 
}

FAQ: Else if statement in Java

Can you use multiple else if statements?

Yes. But remember that if an else if statement is executed, the subsequent ones will not be executed.

How to create an else if statement in Java?

The else if statement is declared with the reserved words else if followed by a logical expression in parentheses (). The logical expression evaluates a condition that is either true or false. The code block to be executed if the condition is true is written inside the curly brackets {}.

Do I have to use else if statements, or can I use several if statements?

You can do that. However, if so, several separate conditional statements are evaluated. An else if statement cooperates with an if statement, while several separate if statements are evaluated separately and can all be fulfilled simultaneously.