Java Switch Statements

In Java, the switch statement is a control flow statement that allows you to select one of several code blocks to be executed based on the value of a single expression. The expression is evaluated once and compared against each of the constant values specified in the case labels.

The basic syntax of a switch statement is as follows:

switch (expression) {
    case value1:
        // code block to be executed if expression == value1
    case value2:
        // code block to be executed if expression == value2
    case value3:
        // code block to be executed if expression == value3
    // more case statements can be added here
        // code block to be executed if

Here’s how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with each case label in turn.
  • If a match is found, the code block associated with that case is executed. Then control transfers to the next statement after the entire switch statement.
  • If no match is found, the default code block is executed (if there is one).
  • The break statement is used to exit the switch statement and continue with the rest of the program.

Let’s see an example:

public class ExampleSwitch {
    public static void main(String[] args) {
        int dayOfWeek = 4;
        String dayName;

        switch (dayOfWeek) {
            case 1:
                dayName = "Monday";
            case 2:
                dayName = "Tuesday";
            case 3:
                dayName = "Wednesday";
            case 4:
                dayName = "Thursday";
            case 5:
                dayName = "Friday";
            case 6:
                dayName = "Saturday";
            case 7:
                dayName = "Sunday";
                dayName = "Invalid day";

        System.out.println("The day is " + dayName);

In this example, we declare an integer variable dayOfWeek and initialize it to 4. We then use a switch statement to determine the name of the day based on the value of dayOfWeek.

In the switch statement, we have seven cases, each of which corresponds to a day of the week. If dayOfWeek is equal to 1, the code in the first case block will be executed, and so on.

Note that each case block ends with a break statement. This is necessary to prevent execution from falling through to the next case block.

If dayOfWeek does not match any of the case labels, the default block will be executed. In this example, the default block sets dayName to “Invalid day”.

Finally, we print out the name of the day using System.out.println(). In this case, the output will be “The day is Thursday”, since dayOfWeek is equal to 4.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial