JB Header

Java switch Statement Tutorial with Examples

Introduction When a decision depends on one variable having one of several fixed values - a day of the week, a menu choice, a command - a long else if ladder becomes repetitive. The switch statement handles this case more clearly. This tutorial explains the classic Java switch statement with examples. We will start with its syntax and how it chooses a case. We will then understand break and fall-through, and use fall-through on purpose to group cases. Next we will switch on strings and enums, and look at the types switch accepts. Lastly, we will go through common mistakes, and see when to use the newer switch expressionsClick to read tutorial: Java Switch Expressions: Arrow Labels and yield instead.

(Note - This tutorial follows Java if, else if and else StatementsClick to read tutorial: Java if, else if and else Statements with Examples.) Syntax of the switch statement
Syntax of the classic switch statement
switch (expression) {
  case value1:
    statements
    break;
  case value2:
    statements
    break;
  default:
    statements
}
Where,
  • expression is evaluated once, and its value is compared with each case label.
  • Execution jumps to the matching case and runs its statements. break then exits the switch.
  • default runs when no case matches. It is optional, and is usually written last.
  • Each case value must be a constant - a literal, a final constant or an enum constant - and no two cases can have the same value.
A simple switch statement
//DayName.java
public class DayName {
  static String dayName(int day) {
    String name;
    switch (day) {
      case 1:
        name = "Monday";
        break;
      case 2:
        name = "Tuesday";
        break;
      case 3:
        name = "Wednesday";
        break;
      case 4:
        name = "Thursday";
        break;
      case 5:
        name = "Friday";
        break;
      case 6:
        name = "Saturday";
        break;
      case 7:
        name = "Sunday";
        break;
      default:
        name = "Invalid day";
    }
    return name;
  }

  public static void main(String[] args) {
    System.out.println("3 -> " + dayName(3));
    System.out.println("7 -> " + dayName(7));
    System.out.println("9 -> " + dayName(9));
  }
}
 OUTPUT of the above code
3 -> Wednesday
7 -> Sunday
9 -> Invalid day
break and fall-through The case labels are only entry points. Once execution has jumped to a matching case, it keeps running the statements below it - including the statements of the following cases - until it reaches a break or the end of the switch. This is called fall-through. Forgetting a break is the most common switch bug -
A missing break causes fall-through
//FallThroughBug.java
public class FallThroughBug {
  public static void main(String[] args) {
    int level = 2;
    switch (level) {
      case 1:
        System.out.println("Level 1: Beginner");
      case 2:
        System.out.println("Level 2: Intermediate");
      case 3:
        System.out.println("Level 3: Advanced");
      default:
        System.out.println("Unknown level");
    }
  }
}
 OUTPUT of the above code
Level 2: Intermediate
Level 3: Advanced
Unknown level
Execution entered at case 2, and with no break statements it fell through every case below it, including default. Using fall-through to group cases Fall-through is useful when several values should run the same code. Stack their case labels with no statements between them. A single case can also list several values, separated by commas, since Java 14.
Grouping cases that share code
//DaysInMonth.java
public class DaysInMonth {
  static int daysIn(int month, boolean leapYear) {
    int days;
    switch (month) {
      case 4:
      case 6:
      case 9:
      case 11:
        days = 30;
        break;
      case 2:
        days = leapYear ? 29 : 28;
        break;
      case 1, 3, 5, 7, 8, 10, 12:      // several values in one case (Java 14+)
        days = 31;
        break;
      default:
        days = -1;
    }
    return days;
  }

  public static void main(String[] args) {
    System.out.println("April    : " + daysIn(4, false));
    System.out.println("February : " + daysIn(2, true));
    System.out.println("October  : " + daysIn(10, false));
  }
}
 OUTPUT of the above code
April    : 30
February : 29
October  : 31
Switching on strings and enums A switch works with these types -
  • int, short, byte and char, and their wrapper classes;
  • String (since Java 7) - compared with equals(), so the match is case-sensitive;
  • enum types - the case labels use the constant names without the enum's name, such as case SATURDAY.
long, float, double and boolean cannot be switched on in a classic switch.
Switching on a String and an enum
//CommandSwitch.java
public class CommandSwitch {
  enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

  public static void main(String[] args) {
    String command = "stop";
    switch (command.toLowerCase()) {
      case "start":
        System.out.println("Starting the engine");
        break;
      case "stop":
        System.out.println("Stopping the engine");
        break;
      default:
        System.out.println("Unknown command: " + command);
    }

    Day today = Day.SATURDAY;
    switch (today) {
      case SATURDAY:
      case SUNDAY:
        System.out.println(today + " is a weekend day");
        break;
      default:
        System.out.println(today + " is a weekday");
    }
  }
}
 OUTPUT of the above code
Stopping the engine
SATURDAY is a weekend day
Explanation of the code
  • command.toLowerCase() makes the match case-insensitive, so "STOP" would also match "stop".
  • Switching on a null String or enum throws a NullPointerException in a classic switch, so make sure the value is not null.
  • Enums are a natural fit for switch. You can read more about them in The Complete Java Enums TutorialClick to read tutorial on Java Enums.
Common mistakes and best practices
  • Missing break: end every case with break (or return), unless you mean to fall through. If you do, add a // fall through comment so readers know it is deliberate.
  • Duplicate or non-constant case values: both are compile errors. A case label cannot be a variable.
  • Variables shared between cases: all cases share one block, so a variable declared in one case is visible - but not initialized - in the cases after it. Wrap a case's statements in braces { } to give it its own scope.
  • Always include default, even if it only reports an unexpected value. It catches values you did not anticipate.
  • Consider a switch expression: since Java 14, switch with arrow labels (case 1 ->) never falls through, can return a value, and is checked for missing cases. It is the better choice for most new code.
Summary In this tutorial we first looked at the syntax of the classic switch statement, which jumps to the case matching a value, and runs default when none matches. We then saw how a missing break causes fall-through, and used fall-through on purpose to group cases, along with comma-separated case values. Next we switched on strings and enums, and listed the types a switch accepts. Lastly, we went through common mistakes and best practices. In the next tutorial, we will look at the modern switch expressions with arrow labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield.