Switch Statement in Java: Syntax, Examples

The switch statement in Java is a powerful control flow statement used to execute different blocks of code based on the value of a single variable or expression. It can be used as an alternative to an if-else-if ladder statement.

The switch statement evaluates an expression and executes the corresponding case block that matches the value of the expression. This approach makes the code cleaner, more readable, and easier to maintain.

Switch statement in Java with basic syntax and examples.

Why Use Switch Statement in Java?

You can use the switch statement in Java programming for the following reasons:

  • Improves code readability.
  • Faster execution in some cases.
  • Provides a cleaner alternative to multiple if-else statements.
  • Ideal when checking a single variable against many fixed values.

Basic Syntax of Switch Statement in Java

The basic syntax for defining a switch statement in Java is as follows:

switch (expression) {
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    // Additional cases...
    default:
        // Code to execute if no case matches
}

In the above syntax,

  • switch is a keyword used to define a switch statement.
  • expression must return a value of type byte, short, char, int, long, enums, String, or wrapper classes (Integer, Short, Byte, Long).
  • case represents a possible value of the expression.
  • break stops the execution from falling into the next case.
  • default executes if no case matches (optional but recommended).

Working of Switch Statement in Java

The switch statement in Java works by evaluating a single expression and then comparing its value with multiple case labels. When a matching case is found, the corresponding block of code is executed.

The execution continues until a break statement is encountered or the switch block ends. If no case matches the expression, the default block (if present) is executed.

Step-by-Step Working

  • The expression inside the switch statement is evaluated once.
  • The value of the expression is compared with each case value.
  • If a matching case is found, the code inside that case executes.
  • The break statement stops further execution and exits the switch block.
  • If no case matches, the default case executes (if defined).

Example: Working of Switch Statement

Let us take a simple example in which we will understand the working of the switch statement.

package switchProgram;
public class SwitchExample {
public static void main(String[] args) {
   int choice = 2;
   switch (choice) {
       case 1:
            System.out.println("Option One Selected.");
            break;
       case 2:
            System.out.println("Option Two Selected.");
            break;
       case 3:
            System.out.println("Option Three Selected.");
            break;
       default:
            System.out.println("Invalid Option");
   }
  }
}

Output:

Option Two Selected.

In this example:

  • The variable choice is assigned the value 2.
  • The switch statement evaluates the value of choice.
  • The value matches the case 2.
  • The corresponding message is printed on the console.
  • The break statement exits the switch block.
  • Since a match is found, the default case is not executed.

Basic Example of Switch Statement

Let us take some basic examples based on the use of switch statement in Java.

Example 1: Switch Statement with Integer

package switchProgram;
public class SwitchExample1 {
  public static void main(String[] args) {
     int number = 2;
     switch (number) {
         case 1:
              System.out.println("Number is One");
              break;
         case 2:
              System.out.println("Number is Two");
              break;
         case 3:
              System.out.println("Number is Three");
              break;
         default:
              System.out.println("Invalid Number");
     }
  }
}

Output:

Number is Two

In this example:

  • The value of variable number is 2.
  • The switch statement compares number with each case.
  • The case 2 matches, so its code executes.
  • Break statement exits the switch block.
  • Other cases are skipped.

Example 2: Switch Statement with String

package switchProgram;
public class SwitchExample2 {
  public static void main(String[] args) {
     String day = "Monday";
     switch (day) {
         case "Monday":
              System.out.println("Start of the week");
              break;
         case "Friday":
              System.out.println("End of the work week");
              break;
         case "Sunday":
              System.out.println("Holiday");
              break;
         default:
              System.out.println("Invalid Day");
     }
  }
}

Output:

Start of the week

Starting with Java 7, you can also use string values in the switch statement. In this example, we have used string values in switch statements. The value “Monday” matches case “Monday” and the corresponding message is printed on the console. The break statement stops further checking.

Example 3: Switch Statement with Character

package switchProgram;
public class SwitchExample4 {
  public static void main(String[] args) {
     char grade = 'A';
     switch (grade) {
          case 'A':
               System.out.println("Excellent");
               break;
          case 'B':
               System.out.println("Good");
               break;
          case 'C':
               System.out.println("Average");
               break;
          default:
               System.out.println("Fail");
     }
  }
}

Output:

Excellent

In this example:

  • The switch expression is a char.
  • The value ‘A’ matches case ‘A’ and the corresponding message inside the block is printed.

Switch Statement Without break in Java

A switch statement without a break statement leads to fall-through execution, where multiple case blocks run after a match. When a break statement is not used inside a switch case, the program does not stop execution after a matching case. It continues executing the code of the next cases, regardless of whether they match the expression. This behavior is known as fall-through.

How Fall-Through Works?

  • The switch expression is evaluated.
  • When a matching case is found, its block of code executes.
  • Since there is no break statement, the execution continues to the next case.
  • All subsequent cases (including default) are executed until the switch block ends or a break statement is encountered.

Example 4: Switch Statement Without Break

package switchProgram;
public class SwitchWithoutBreak {
  public static void main(String[] args) {
     int number = 1;
     switch (number) {
         case 1:
              System.out.println("Case 1");
         case 2:
              System.out.println("Case 2");
         case 3:
              System.out.println("Case 3");
         default:
              System.out.println("Default Case");
     }
  }
}

Output:

Case 1
Case 2
Case 3
Default Case

In this example:

  • The value of variable number is 1.
  • case 1 matches the value and the corresponding code block is executed.
  • Since there is no break statement, the execution continues to:
    • case 2
    • case 3
    • default
  • All print statements are executed sequentially. This is called fall-through behavior.

Switch Statement with Enum in Java

In Java, an enum (stands for enumeration) is a special data type that represents a fixed set of constants. If you use an enum with a switch statement, it makes the code more readable, type-safe, and less error-prone compared to using numeric or string values. Using enum with switch statements offer the following benefits:

  • Prevents invalid values at compile time.
  • Improves code readability.
  • Makes programs easier to maintain.
  • Commonly used for fixed options like days, levels, states, or commands.

Example 5: Switch Statement with Enum

package switchProgram;
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class SwitchWithEnum {
  public static void main(String[] args) {
    Day today = Day.FRIDAY;
    switch (today) {
        case MONDAY:
               System.out.println("Start of the work week");
               break;
        case FRIDAY:
               System.out.println("End of the work week");
               break;
        case SATURDAY:
        case SUNDAY:
               System.out.println("Weekend");
               break;
        default:
               System.out.println("Midweek day");
    }
  }
}

Output:

End of the work week

In this example:

  • We have defined a variable named Day of type enum with a fixed set of constants.
  • Then, we have defined a variable today and assigned Day.FRIDAY.
  • The switch statement evaluates the enum value.
  • Since case FRIDAY matches the value of today, the corresponding message is displayed on the console.
  • The break statement stops further execution of the switch block.

Important Rules for Using Enum in Switch Statement

There are some important rules for using enum in switch statement in Java that you should keep in mind.

  • Case labels must be enum constants (no quotes).
  • Enum values are implicitly static and final.
  • Only values from the same enum type are allowed.
  • default is optional but recommended.

Using a switch statement with enum is a best practice in Java when working with a fixed set of values. It results in cleaner, safer, and more maintainable code compared to using integers or strings.

Nested Switch Statement in Java

A nested switch statement in Java means placing one switch statement inside another switch statement. When you place a switch statement inside another switch, it is called nested switch statement in Java. It is used when a decision needs to be made based on multiple conditions, where the second condition depends on the first one.

Example 6: Nested Switch Statement

package switchProgram;
public class NestedSwitchExample {
  public static void main(String[] args) {
     int year = 2;
     int semester = 1;
  // Outer switch statement
     switch (year) {
         case 1:
              System.out.println("First Year");
              break;
         case 2:
           // Inner switch statement
              switch (semester) {
                  case 1:
                       System.out.println("Second Year - Semester 1");
                       break;
                  case 2:
                       System.out.println("Second Year - Semester 2");
                       break;
                  default:
                       System.out.println("Invalid Semester");
              }
              break;
          case 3:
               System.out.println("Third Year");
               break;
          default:
               System.out.println("Invalid Year");
     }
  }
}

Output:

Second Year - Semester 1

In this example:

  • The outer switch statement evaluates the value of year.
  • case 2 matches, so the inner switch statement executes.
  • The inner switch statement evaluates the value of semester.
  • case 1 matches and prints the message on the console.
  • The break statements ensure proper exit from each switch.

Key Points to Remember

  • Nested switch statement increases complexity, so you should use it only when necessary.
  • Always use break to avoid fall-through.
  • Indentation and formatting are important for readability.
  • Nested switch works with all supported switch data types.

Switch Statement in Java 12

Java 12 introduced an enhanced switch statement, also called a switch expression. It is a modern and improved version of the traditional switch statement. This new form of switch makes the code more concise, safe, and expressive compared to the traditional switch statement.

The important key features of this switch statement in Java are:

  • Uses arrow (->) syntax instead of colon (:).
  • No need for break statements.
  • Prevents accidental fall-through.
  • Can return a value.
  • Cleaner and more readable code.

Note: Switch expressions were introduced as a preview feature in Java 12 and became standard in Java 14.

Syntax of Enhanced Switch Statement (Java 12+)

The modern syntax of enhanced switch statement in Java is as:

result = switch (expression) {
    case value1 -> result1;
    case value2 -> result2;
    default -> defaultResult;
};

Syntax with Multiple Case Labels

result = switch (expression) {
    case value1, value2 -> result1;
    case value3 -> result2;
    default -> defaultResult;
};

Important Syntax Rules

  • No break statements are required.
  • Fall-through is not allowed.
  • Each case must return a value.
  • yield is used instead of return inside switch blocks.
  • default is required unless all cases are covered.

Example 7: Basic Use

package switchProgram;
public class SwitchExpressionExample {
   public static void main(String[] args) {
      int day = 3;
      String dayName = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            default -> "Weekend";
      };
      System.out.println(dayName);
  }
}

Output:

Wednesday

In this example:

  • The switch expression evaluates the value of day.
  • case 3 matches and returns “Wednesday”.
  • The returned value is stored in a variable named dayName.
  • No break statement is required to stop further execution.

Example 8: Multiple Case Labels

Java 12 allows multiple values in a single case.

package switchProgram;
public class SwitchExpressionExample {
  public static void main(String[] args) {
     int month = 1;
     String season = switch (month) {
         case 12, 1, 2 -> "Winter";
         case 3, 4, 5 -> "Summer";
         case 6, 7, 8 -> "Monsoon";
         case 9, 10, 11 -> "Autumn";
         default -> "Invalid Month";
     };
     System.out.println(season);
  }
}

Output:

Winter

Example 9: Using yield in Switch Expression

When a case needs multiple statements, use the yield keyword in switch expression.

package switchProgram;
public class YieldExample {
   public static void main(String[] args) {
      int marks = 85;
      String grade = switch (marks / 10) {
            case 9, 10 -> {
                yield "A";
            }
            case 8 -> {
                yield "B";
            }
            case 7 -> {
                yield "C";
            }
            default -> {
                yield "Fail";
            }
      };
      System.out.println(grade);
   }
}

Output:

B

Conclusion

The switch statement in Java is a clean, efficient, and powerful way to handle multiple conditions based on the value of a single variable. With the introduction of enhanced switch expressions, Java has made switch statement shorter, safer, and more expressive. We hope that you will have understood the basic syntax of switch statement and practiced all examples.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *