Java Conditional Statements

Previously, we have learned about operators that are used to make decisions. While programming, we might require to execute a certain set of instructions based on these decisions. This can be done with the help of Conditional Statements. In this unit, we will learn about if, else, and else if conditional statements.

1. If...Else Statement

The if...else conditional statement works similar to that in Python. When an if...else conditional statement is used, the if block of code executes when the condition is true, otherwise the else block of code is executed.

Syntax

if (condition) {

  // block of code to be executed if the condition is true

} else {

  // block of code to be executed if the condition is false

}

 

1.1 Using If...Else

Let's take a look at how to use if...else statements with the help of examples.

Example 1:

class VendingMachine {

    public static void main(String[] args) {

        int token = 20;

 

        if (token == 20) {

            System.out.println("Collect Water Bottle");

        } else {

            System.out.println("Invalid Token");

        }

    }

 

 

Output

Collect Water Bottle

 

In the above code, we have a vending machine (a machine that dispenses small items such as food, drinks, etc when a coin or token is inserted). When a token of value 20 is inserted, the condition token == 20 evaluates to true and displays the Collect  Water Bottle message on the console. If a token other than 20 is inserted, the condition evaluates to false and an error message Invalid Token is displayed. 

 

Example 2:

class VendingMachine {

    public static void main(String[] args) {

        int token = 30;

 

        if (token == 20) {

            System.out.println("Collect Water Bottle");

        } else {

            System.out.println("Invalid Token");

        }

    }

}

 

Output

Invalid Token

 

Here, the condition token == 20 evaluates to false. Hence, the else block of code is executed and the Invalid Token text is displayed on the console.

 

2. Else if Statement

Similar to elif in Python, Java provides an else if statement to have multiple conditional statements between if and else The else if statement is optional. We can add any number of else if statements after the if conditional block.

Syntax

if (condition1) {

  // block of code to be executed if condition1 is true

} else if (condition2) {

  // block of code to be executed if the condition1 is false and condition2 is true

} else {

  // block of code to be executed if the condition1 is false and condition2 is false

}

 

2.1 Execution of Else if Statement

Java will start executing from the if block and then step-by-step checks every conditional statement. If any condition evaluates to true, the corresponding block of code will be executed. If no conditional statement evaluates to true, then else block will be executed.

Example

class VendingMachine {

    public static void main(String[] args) {

        int token = 30;

 

        if (token == 10) {

            System.out.println("Collect Chips");

        } else if(token == 20) {

            System.out.println("Collect Water Bottle");

        } else if(token == 30) {

            System.out.println("Collect Soft Drink");

        } else {

            System.out.println("Invalid Token");

        }

    }

}

 

Output

Collect Soft Drink

In the above code, the vending machine now has many options and it dispenses various items based on the token inserted.

Example

token = 30

 

if (token == 10):

    print("Collect Chips")

elif(token == 20):

    print("Collect Water Bottle")

elif(token == 30):

    print("Collect Soft Drink")

else:

    print("Invalid Token")

 

Output

Collect Soft Drink

 

There can be a situation where multiple conditional statements will evaluate to true then only the first block whose condition evaluates to true will be executed. Let's take an example, that our vending machine dispenses two types of drinks Sprite and Fanta at the same cost.

Example

class VendingMachine {

    public static void main(String[] args) {

        int token = 30;

 

        if (token == 30) {

            System.out.println("Collect Sprite");

        } else if (token == 30) {

            System.out.println("Collect Fanta");

        } else {

            System.out.println("Invalid Token");

        }

    }

}

 

Output

Collect Sprite

Here, both the conditions at Sprite and Fanta will evaluate to be true. But in the execution order when the first condition at Sprite evaluates to true, the corresponding block is executed and the program skips the remaining conditional statements.

 

3. Nested Conditions

The conditional statements inside another if...else conditional statement is called a nested conditional statement. Let's look at an example with nested conditions,

Example

class VendingMachine {

    public static void main(String[] args) {

        int token = 30;

        char softDrink = 'S';

 

        if (token == 30) {

            if (softDrink == 'S') {

                System.out.println("Collect Sprite");

            } else if (softDrink == 'F') {

                System.out.println("Collect Fanta");

            } else {

                System.out.println("Invalid Option");

            }

        } else {

            System.out.println("Invalid Token");

        }

    }

}

 

Output

Collect Sprite

In the above example, the nested if block is used to provide the required item based on the soft drink option provided.

 

4. Optional Else Statement

The else statement is not compulsory after if...else if statements.

Example

class VendingMachine {

    public static void main(String[] args) {

        int token = 30;

        char softDrink = 'S';

 

        if (token == 30) {

            if (softDrink == 'S') {

                System.out.println("Collect Sprite");

            } else if (softDrink == 'F') {

                System.out.println("Collect Fanta");

            }

        }

    }

}

 

Output

Collect Sprite

 

5. Possible Mistakes

5.1 Possible Mistakes in If...Else

The else can only be used along with if condition. It should be written below if conditional block.

Error Code

class Main {

   public static void main(String[] args) {

      if (false) {

         System.out.println("If Block");

      }

      System.out.println("After If");

      else {

         System.out.println("Else Block");

      }

      System.out.println("After Else");

   }

 

Output

file.java:7: error: 'else' without 'if'

      else {

      ^

 

We can write above wrong code to execute properly by below code

class Main {

    public static void main(String[] args) {

        if (false) {

            System.out.println("If Block");

        } else {

            System.out.println("Else Block");

        }

        System.out.println("After Else");

    }

}

 

Output

Else Block

After Else

 

No code is allowed in between if conditional block and else statement.

 

5.2 Possible Mistakes in Else if

The else if statement cannot occur after the else block. Let's look at the vending machine.

Wrong Code

class VendingMachine {

    public static void main(String[] args) {

        int token = 20;

 

        if (token == 10) {

            System.out.println("Collect Chips");

        } else if (token == 20) {

            System.out.println("Collect Water Bottle");

        } else {

            System.out.println("Invalid Token");

        } else if (token == 30) {

            System.out.println("Collect Soft Drink");

        }

    }

}

 

Output

file.java:11: error: 'else' without 'if'

   } else if (token == 30) {

       ^

1 error

 

We can write above wrong code to execute properly by below code

class VendingMachine {

    public static void main(String[] args) {

        int token = 20;

 

        if (token == 10) {

            System.out.println("Collect Chips");

        } else if (token == 20) {

            System.out.println("Collect Water Bottle");

        } else if (token == 30) {

            System.out.println("Collect Soft Drink");

        } else {

            System.out.println("Invalid Token");

        }

    }

}

 

 

Output

Collect Water Bottle

 

6. If...Else Statement without Curly Braces

Curly braces inside an if...else block can be omitted for blocks that have only a single statement.

Example

class VendingMachine {

    public static void main(String[] args) {

        int token = 20;

 

        if (token == 20) System.out.println("Collect Water Bottle");

        else System.out.println("Invalid Token");

    }

}

 

Output

Collect Water Bottle

 

Conclusion:

  • When an  if...else conditional statement is used, the if block executes when the condition is true otherwise the else block of code is executed.

  • The else if statement can be used to insert multiple conditions between if and else statements.

  • The else statement is not compulsory after if...else if statements.

  • The else if and else statements cannot be used without the if statement