Lesson 19. Switch ... Case Statement in Java | Learn Basic Java

Published on
Belongs to Category: Learn Basic Java|Posted by: Le Thanh Giang||6 min read
Facebook share iconLinkedIn share iconTwitter share iconPinterest share iconTumblr share icon
Lesson 19. Switch ... Case Statement in Java | Learn Basic Java

What is the Switch ... Case Statement in Java?

In Java programming, the switch statement is an important tool for performing comparisons and conditions. Instead of using multiple if...else statements to check various conditions, the switch statement helps make the code more concise and easier to understand. It is typically used when you need to check the value of a variable against a list of possible values and perform corresponding actions.

In this article, we will explore how to use the switch ... case statement in Java, the basic syntax, practical examples, and things to keep in mind when using it.

Basic Syntax of the Switch Statement

The basic syntax of the switch statement in Java is as follows:

switch (variable) {
    case value_1:
        // Perform action when variable == value_1
        break;
    case value_2:
        // Perform action when variable == value_2
        break;
    // Other cases (if needed)
    default:
        // Perform action if no case matches
}

Where:

  • variable: The variable or value to be checked (it can be int, char, String, or other data types).
  • case value_n: Checks if the variable has the value value_n. If true, it executes the code inside that case.
  • break: Used to exit the switch statement. Without break, the program will continue checking the next cases, which may not be desired.
  • default: A default case when no cases match. It is optional but very useful for handling unforeseen situations.

Here is a simple example of how to use the switch statement in Java to check the day of the week and print the corresponding day name:

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3; // Assume the day is Tuesday

        switch (day) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

Output:

Tuesday

In this example, the variable day has the value of 3, and the switch statement will check and print "Tuesday" because day == 3.

Using switch with String

Java supports using String in the switch statement, making it easy to compare text strings.

public class SwitchStringExample {
    public static void main(String[] args) {
        String day = "Tuesday";

        switch (day) {
            case "Sunday":
                System.out.println("Holiday");
                break;
            case "Monday":
                System.out.println("Work day");
                break;
            case "Tuesday":
                System.out.println("Work day");
                break;
            case "Wednesday":
                System.out.println("Work day");
                break;
            default:
                System.out.println("Unknown day");
        }
    }
}

Output:

Work day

Using switch Without break

In some cases, you may want to perform multiple actions for different values without needing a break. This can be done by omitting the break and allowing the program to "fall through" the cases.

public class SwitchFallThrough {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            case 1:
            case 2:
            case 3:
                System.out.println("Weekend is coming");
                break;
            case 4:
            case 5:
                System.out.println("Work day");
                break;
            default:
                System.out.println("Unknown day");
        }
    }
}

Output:

Weekend is coming

In this example, cases 1, 2, and 3 all share the action "Weekend is coming".

Switch Expression (Switch in Newer Java Versions)

Switch Expression is an important improvement introduced in Java 12. Prior to this, the switch statement could only be used as a simple statement. However, with Switch Expression, you can now use switch to return a value, which reduces unwanted issues and makes the code more flexible.

New Syntax for Switch Expression

The new syntax for Switch Expression uses the -> keyword instead of : and no longer requires the break.

int day = 3;
String result = switch (day) {
    case 1 -> "Sunday";
    case 2 -> "Monday";
    case 3 -> "Tuesday";
    case 4 -> "Wednesday";
    case 5 -> "Thursday";
    case 6 -> "Friday";
    case 7 -> "Saturday";
    default -> "Invalid day";
};
System.out.println(result);

Output:

Tuesday

In this example:

  • switch (day): Similar to the traditional switch statement, it checks the value of day.
  • case 1 -> "Sunday";: If day == 1, the expression returns the value "Sunday".
  • default -> "Invalid day";: The default case when no value matches, the expression returns "Invalid day".
  • No break required: When using Switch Expression, you do not need to use break because each case returns a value and terminates immediately.

Switch Expression with Multi-line Expressions

You can also use Switch Expression to perform more complex actions in a block, using yield to return a value in multi-line blocks.

For example, you might want to perform calculations or operations before returning a value:

int month = 4;
String season = switch (month) {
    case 12, 1, 2 -> {
        yield "Winter";
    }
    case 3, 4, 5 -> {
        yield "Spring";
    }
    case 6, 7, 8 -> {
        yield "Summer";
    }
    case 9, 10, 11 -> {
        yield "Fall";
    }
    default -> {
        yield "Invalid month";
    }
};
System.out.println(season);

Output:

Spring

In this example:

  • yield is used to return a value in a multi-line block.
  • You can combine multiple case values (e.g., case 12, 1, 2) for related values.

Benefits of Switch Expression

  • Improved flexibility: You can return values immediately without needing to use break.
  • Easier to handle multiple values: You can combine multiple case values into a single line (such as case 12, 1, 2), making the code shorter and clearer.
  • Increased clarity: You don’t have to worry about missing break statements, which can avoid unintended "fall-through" errors.

Conclusion

The switch statement in Java is a powerful tool for checking and comparing the value of a variable against a set of possible values. It makes the code more concise and easier to understand when handling multiple conditions. However, you need to be cautious when using switch to avoid common errors such as missing break or mistakenly using unsupported data types.

We hope this article has helped you understand how to use the switch ... case statement in Java. Happy coding!

Next article: Article 20. Check the Number of Days in a Month Using Switch ... Case

Latest Posts

Related Posts

Newsletter border

Subscribe to Receive Updates from RiverLee