Java if, else & switch Conditional Control Statements Tutorial

In this Java tutorial we learn to control the flow of our application through the if, else if, else and switch statements.

We also learn how to nest conditional statements inside one another, and use the shorthand method of writing an if statement with the ternary operator.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is conditional control

We can control the flow of our application by evaluating certain conditions. Based on the result of the evaluation, we can then execute certain sections of code.

As an example, let’s consider an application with a member area. To gain access to the member area, a user must provide the correct login credentials.

If the user provides the correct credentials, they are allowed to enter the member area. If not, they are given the option to try again or reset their password.

In pseudocode, the example above would look something like this.

Example:
if username == db_username && password == db_password
    redirect to member area
otherwise
    if forgot_password
        reset password
otherwise
    try_again

The actual code will not look like the example above, but it serves to give you an example of what conditional control is used for.

We can use conditional control in Java through the following statements, in combination with comparisonOpens up in a new page and logicalOpens up in a new page operators.

  • if
  • else if
  • else
  • switch

The if statement in Java

The if statement will evaluate in its header if a condition is true or not.

If the condition proves true, the compiler will execute the code in the if statement’s code block. If the condition proves false, the compiler will move on to the next statement outside and below the code block.

An if statement is written with the keyword if , followed by the condition(s) we want to evaluate between parentheses.

Then, we specify a code block with open and close curly braces that will be executed if the condition proves true.

Syntax:
if (condition) {

    // code to execute
    // if condition is
    // true
}

Note that an if statement itself is not terminated with a semicolon.

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

        byte num1 = 5;
        byte num2 = 5;

        if (num1 == num2) {

            System.out.println(num1 + " is equal to " + num2);
        }
    }
}

In the example above, the if statement compares the two numbers to see if they are the same. Because they are, the message is printed to the console.

If we change one of the numbers to another value, the condition will be false and the message will not be printed.

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

        byte num1 = 5;
        byte num2 = 3;

        if (num1 == num2) {

            System.out.println(num1 + " is equal to " + num2);
        }
    }
}

When we run the example above, nothing is printed to the console because the condition is false and the print statement never gets executed.

The else if ladder in Java

The else if ladder can be used when we want to evaluate extra conditions that relate to our if statement.

To create an else if ladder, we simply add the word else between two if statements, connecting them.

Syntax:
if (condition1) {

    // first condition
    // to be evaluated
}
else if (condition2) {

    // second condition
    // to be evaluated
}

If the first condition proves false, the compiler will evaluate the second before moving on to any other code.

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

        byte num1 = 5;
        byte num2 = 3;

        if (num1 > num2) {

            System.out.println("if statement is true");
            System.out.println(num1 + " is greater than " + num2);

        } else if (num1 < num2) {

            System.out.println("else if statement is true");
            System.out.println(num1 + "is less than " + num2);
        }
    }
}

We use else if ladders to connect our if statements together. We’re sort of grouping them.

Note that an else if statement can only follow an if statement, it cannot stand on its own. The first conditional statement must always be an if.

The else fallback in Java

The else statement acts as a catch-all fallback for anything that isn’t covered by an if statement or an else if ladder.

The else statement doesn’t need a conditional block in the header because it works as a catch-all. We only write the else keyword, followed by its execution block.

Syntax:
if (condition) {

    // code to execute
    // if condition is
    // true
}
else {

    // if above conditions
    // are false, execute
    // this block
}

Like with the else if ladder, the else statement cannot stand on its own. It must follow an if statement or an else if ladder.

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

        byte num1 = 5;
        byte num2 = 5;

        if (num1 > num2) {

            System.out.println("if statement is true");
            System.out.println(num1 + " is greater than " + num2);

        } else if (num1 < num2) {

            System.out.println("else if statement is true");
            System.out.println(num1 + "is less than " + num2);

        } else {

            System.out.println("none of the above is true, execute the else statement");
        }
    }
}

In the example above, our else execution block is executed because both if statements prove false.

How to nest if statements in Java

Java allows us to nest if statements inside other if statements. The compiler will evaluate each if statement in a hierarchical fashion, that’s to say from the outside inwards from top to bottom.

All we do is write an if statement inside the execution block of another if statement.

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

        byte num1 = 10;

        if (num1 < 20) {

            System.out.println("outer if execution");

            if (num1 >= 10) {
                System.out.println("inner if execution");
            }
        }
    }
}

We’re not limited to one nested if statement. We can have as many nested if conditions as we need in one control structure set.

Try not to nest more than three levels deep. Nesting too deep is a bad practice and can be avoided in most situations.

The ternary conditional operator ( ? : ) in Java

When we have an if else statement with only single execution statements, we can use what’s known as the ternary operator as a shorthand method to write it.

To use the ternary operator, we write the condition between parentheses first, followed by a ? operator.

Then, we write the single execution statement if the condition proves true, followed by the : operator.

Finally, we write the single execution statement if the condition proves false, and terminate the whole expression with a semicolon.

Syntax:
 (condition) ? if_true_statement : if_false_statement;

Let’s consider the following if else statement.

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

        byte num = 8;

        if (num == 10) {
            System.out.println("num == 10");
        } else {
            System.out.println("num != 10");
        }
    }
}

In the example above, we evaluate if a number is 10 or not, and print a message to the console. Let’s convert this into shorthand with the ternary operator.

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

        byte num = 5;

        // resul        condition     if true statement   if false statement
        String result = (num == 10) ? "num == 10"       : "num != 10";

        System.out.println(result);
    }
}

It may seem confusing at first, especially if you’ve only been writing traditional if statements for a while, but with practice it becomes second nature.

It’s important to note that many developers do not like to use the ternary operator because it makes the code harder to read, especially for new programmers. It can also result in impenetrably complex expressions. Some employers even disallow its use altogether.

For this reason, we’ll only be using traditional if else statements throughout this tutorial course, but feel free to practice the ternary in case you come across it in the wild.

The switch statement in Java

We use the switch statement when we want to compare a single value against a list of many other values.

Before we explain how it works, let’s look at the syntax first.

Syntax:
switch (main_value) {

    case check_against_value1 :
        // if true execute this code
        break;
    case check_against_value2 :
        // if true execute this code
        break;

    default:
        // if none of the cases are true
}

First, we specify the main value that we will be comparing other values against. Then, in the code block, we specify our cases.

A case consists of the value we want to compare against the main value, and execution code after the : if the comparison proves true.

The break keyword tells the compiler that we’ve found what we’re looking for in the switch, so it can break out of it and continue on to code outside and below the switch.

The default case acts as our fallback statement, much like an else statement. In fact, the switch statement above is comparable to the following if statement.

Syntax:
if (main_value == check_against_value1) {

    // if true execute this code
} else if (main_value == check_against_value2) {

    // if true execute this code
} else {

    // if none of the cases are true
}

Let’s see a real world example.

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

        char grade = 'B';

        switch (grade) {

            case 'A':
                System.out.println("You got an A. Excellent!");
                break;
            case 'B':
                System.out.println("You got a B. Good Job.");
                break;
            case 'C':
                System.out.println("You got a C. Well done.");
                break;
            case 'D':
                System.out.println("You got a D. You passed.");
                break;
            case 'F':
                System.out.println("You got an F. Sorry, you failed.");
                break;


            default:
            System.out.println("Grade N/A");
        }
    }
}

In the example above, we have a single main value (grade) that’s being evaluated against multiple cases. When a case evaluates to true, the execution statement after the colon executes.

Typically a switch statement is only used when we want to compare one value to many others.

Switch expressions & arrow labels in Java

Java 12 and up allows us to use switch expressions. A switch expression is where the result of the comparison is assigned to a variable.

Essentially, we use switch expressions when we want to return a value from the switch into a variable.

To create the expression, we assign the switch statement to a variable. Inside the switch statement, where we specify our cases, we replace the colon with an arrow label -> , followed by the value we want to return into the variable.

In a switch expression, we don’t use the break keyword.

Syntax:
data_type variable_name = switch (main_value) {

    case check_against_value1 -> value_to_return;
    case check_against_value2 -> value_to_return;

    // fallback
    default -> value_to_return;
}
Example:
public class Program {
    public static void main(String[] args) {

        char grade = 'B';

        String gradeMsg = switch (grade) {

            case 'A' -> "You got an A. Excellent!";
            case 'B' -> "You got a B. Good Job.";
            case 'C' -> "You got a C. Well done.";
            case 'D' -> "You got a D. You passed.";
            case 'F' -> "You got an F. Sorry, you failed.";

            default  -> "Grade N/A";
        };

        System.out.println(gradeMsg);
    }
}

In the example above, we assign our switch statement to a variable called ‘gradeMsg’ to create the expression.

Then, we replce the colon with an arrow label in all the cases and remove the break keyword to return the value into ‘gradeMsg’.

Previously, the message for each grade was printed directly to the console. This time it’s stored in ‘gradeMsg’ and we can do something with it.

Switch expressions & the yield keyword in Java

Java 13 and up allows us to yield (return) values from a switch expression. We can now use either the yield keyword or the arrow labels from Java 12.

We specify our case, followed by a colon and the yield keyword. Then we specify the value we want to return to the variable.

Syntax:
data_type variable_name = switch (main_value) {

    case check_against_value1: yield value_to_return;
    case check_against_value2: yield value_to_return;

    // fallback
    default: yield value_to_return;
}
Example:
public class Program {
    public static void main(String[] args) {

        char grade = 'B';

        String gradeMsg = switch (grade) {

            case 'A': yield "You got an A. Excellent!";
            case 'B': yield "You got a B. Good Job.";
            case 'C': yield "You got a C. Well done.";
            case 'D': yield "You got a D. You passed.";
            case 'F': yield "You got an F. Sorry, you failed.";


            default: yield "Grade N/A";
        };

        System.out.println(gradeMsg);
    }
}

In the example above we use a colon and the yield keyword to return a value into ‘gradeMsg’.

We can wrap our case execution code in a code block, allowing for multiple statements along with the yield.

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

        char grade = 'B';

        String gradeMsg = switch (grade) {

            case 'A': {
                yield "You got an A. Excellent!";
            }
            case 'B': {
                yield "You got a B. Good Job.";
            }
            case 'C': {
                yield "You got a C. Well done.";
            }
            case 'D': {
                yield "You got a D. You passed.";
            }
            case 'F': {
                yield "You got an F. Sorry, you failed.";
            }


            default: {
                yield "Grade N/A";
            }
        };

        System.out.println(gradeMsg);
    }
}

This also allows us to use arrow labels instead of colons, if we prefer.

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

        char grade = 'B';

        String gradeMsg = switch (grade) {

            case 'A' -> {
                yield "You got an A. Excellent!";
            }
            case 'B' -> {
                yield "You got a B. Good Job.";
            }
            case 'C' -> {
                yield "You got a C. Well done.";
            }
            case 'D' -> {
                yield "You got a D. You passed.";
            }
            case 'F' -> {
                yield "You got an F. Sorry, you failed.";
            }

            default -> {
                yield "Grade N/A";
            }
        };

        System.out.println(gradeMsg);
    }
}

Summary: Points to remember

  • We control the flow of our application with if, else if, else and switch conditional control statements.
  • The else if ladder and else statement cannot stand on their own, they must be part of an if statement.
  • The else statement represents everything that the if and else if statements do not cover.
  • We can nest conditionals by writing them inside the execution blocks of other conditionals.
  • The ternary operator is a shorthand method of writing an if else statement with only a single execution statement.
  • A switch statement is used to compare one value against many.