DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 2: Traditional `switch` Statement

In Part 1, we learned how the if-else statement helps Java make decisions based on boolean conditions.

However, when you need to choose between multiple fixed values, writing long chains of if-else if-else statements can make your code difficult to read and maintain.

That's where the switch statement comes in.


What Is the switch Statement?

The switch statement allows you to execute different blocks of code based on the value of an expression.

It is often cleaner and more readable than multiple if-else statements when comparing a variable against several possible values.


Example

Instead of writing

String day = "MONDAY";

if (day.equals("MONDAY")) {
    System.out.println("Start of the work week");
}
else if (day.equals("TUESDAY")) {
    System.out.println("Second working day");
}
else if (day.equals("WEDNESDAY")) {
    System.out.println("Midweek");
}
else {
    System.out.println("Weekend or another day");
}
Enter fullscreen mode Exit fullscreen mode

You can write

String day = "MONDAY";

switch (day) {

    case "MONDAY":
        System.out.println("Start of the work week");
        break;

    case "TUESDAY":
        System.out.println("Second working day");
        break;

    case "WEDNESDAY":
        System.out.println("Midweek");
        break;

    default:
        System.out.println("Weekend or another day");
}
Enter fullscreen mode Exit fullscreen mode

The switch version is easier to read and maintain.


Syntax

switch (expression) {

    case value1:
        // statements
        break;

    case value2:
        // statements
        break;

    default:
        // default statements
}
Enter fullscreen mode Exit fullscreen mode

Supported Data Types

The types supported by switch have evolved over different Java versions.

Java Version Supported Types
Java 1.4 and earlier byte, short, char, int
Java 5 Wrapper classes (Byte, Short, Character, Integer) and enum
Java 7 and later String

Note: Types such as long, float, double, and boolean are not supported in a traditional switch statement.


Rule 1: Curly Braces Are Mandatory

Unlike an if statement, curly braces cannot be omitted.

Correct

int choice = 1;

switch (choice) {

    case 1:
        System.out.println("One");
}
Enter fullscreen mode Exit fullscreen mode

Incorrect

switch (choice)
    case 1:
        System.out.println("One");
Enter fullscreen mode Exit fullscreen mode

Compile-time error


Rule 2: case and default Are Optional

A switch statement may contain:

  • Only case
  • Only default
  • Both
  • Neither

Even an empty switch is valid.

int option = 1;

switch (option) {

}
Enter fullscreen mode Exit fullscreen mode

This compiles successfully.


Rule 3: Every Statement Must Belong to a case or default

Incorrect

int choice = 1;

switch (choice) {

    System.out.println("Hello");

    case 1:
        System.out.println("One");
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

case, default, or '}' expected
Enter fullscreen mode Exit fullscreen mode

Every executable statement inside a switch block must belong to a case or default label.


Rule 4: Every case Label Must Be a Compile-Time Constant

Correct

int choice = 2;

switch (choice) {

    case 1:
        System.out.println("One");
        break;

    case 2:
        System.out.println("Two");
}
Enter fullscreen mode Exit fullscreen mode

Incorrect

int option = 2;

int value = 2;

switch (option) {

    case value:
        System.out.println("Two");
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

constant expression required
Enter fullscreen mode Exit fullscreen mode

Why?

The compiler does not know the value of value during compilation.


Using final

int option = 2;

final int VALUE = 2;

switch (option) {

    case VALUE:
        System.out.println("Two");
}
Enter fullscreen mode Exit fullscreen mode

This works because a final variable initialized with a constant becomes a compile-time constant.


Rule 5: Case Labels Must Be Within Range

Consider a byte.

byte number = 10;

switch (number) {

    case 10:
        System.out.println("Ten");

    case 100:
        System.out.println("Hundred");
}
Enter fullscreen mode Exit fullscreen mode

This compiles because both values fit into the range of a byte.


Now try

byte number = 10;

switch (number) {

    case 1000:
        System.out.println("Thousand");
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

possible lossy conversion from int to byte
Enter fullscreen mode Exit fullscreen mode

Since 1000 cannot fit into a byte, Java rejects it.


Rule 6: Duplicate case Labels Are Not Allowed

char letter = 'a';

switch (letter) {

    case 97:
        System.out.println("ASCII");

    case 'a':
        System.out.println("Character");
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

duplicate case label
Enter fullscreen mode Exit fullscreen mode

Why?

Because

'a' = 97
Enter fullscreen mode Exit fullscreen mode

Both labels represent the same value.


Understanding Fall-Through

One of the most important concepts in a traditional switch statement is fall-through.

When a matching case is found, execution continues until:

  • a break statement is encountered, or
  • the switch block ends.

Example

int number = 0;

switch (number) {

    case 0:
        System.out.println("Zero");

    case 1:
        System.out.println("One");
        break;

    case 2:
        System.out.println("Two");

    default:
        System.out.println("Default");
}
Enter fullscreen mode Exit fullscreen mode

Output

Zero
One
Enter fullscreen mode Exit fullscreen mode

Why?

Execution starts at case 0.

Since there is no break, execution continues into case 1.

The break stops further execution.


Output Table

Value Output
0 Zero, One
1 One
2 Two, Default
3 Default

Why Is Fall-Through Useful?

Sometimes multiple cases should perform the same action.

Example

char grade = 'B';

switch (grade) {

    case 'A':

    case 'B':

    case 'C':
        System.out.println("Pass");
        break;

    default:
        System.out.println("Fail");
}
Enter fullscreen mode Exit fullscreen mode

Output

Pass
Enter fullscreen mode Exit fullscreen mode

This avoids duplicate code.


The default Case

The default block executes when no case matches.

int option = 10;

switch (option) {

    case 1:
        System.out.println("One");
        break;

    default:
        System.out.println("Invalid option");
}
Enter fullscreen mode Exit fullscreen mode

Output

Invalid option
Enter fullscreen mode Exit fullscreen mode

Does default Have to Be Last?

No.

Although placing it last is the standard convention, Java allows it anywhere.

Example

int number = 3;

switch (number) {

    default:
        System.out.println("Default");

    case 1:
        System.out.println("One");
        break;

    case 2:
        System.out.println("Two");
}
Enter fullscreen mode Exit fullscreen mode

Output

Default
One
Enter fullscreen mode Exit fullscreen mode

Since default matches first and there is no break, execution falls through into the next case.


switch with enum

Support for enum was introduced in Java 5.

enum Coffee {

    ESPRESSO,
    LATTE,
    CAPPUCCINO,
    AMERICANO

}
Enter fullscreen mode Exit fullscreen mode
Coffee coffee = Coffee.CAPPUCCINO;

switch (coffee) {

    case ESPRESSO:
        System.out.println("Strong coffee");
        break;

    case LATTE:
        System.out.println("Milk coffee");
        break;

    case CAPPUCCINO:
        System.out.println("Foamy coffee");
        break;

    case AMERICANO:
        System.out.println("Black coffee");
        break;
}
Enter fullscreen mode Exit fullscreen mode

Output

Foamy coffee
Enter fullscreen mode Exit fullscreen mode

Notice that we write

case CAPPUCCINO:
Enter fullscreen mode Exit fullscreen mode

not

case Coffee.CAPPUCCINO:
Enter fullscreen mode Exit fullscreen mode

Case labels must use unqualified enum constants.


switch with String

Java 7 introduced support for String.

String browser = "Chrome";

switch (browser) {

    case "Chrome":
        System.out.println("Google Chrome");
        break;

    case "Firefox":
        System.out.println("Mozilla Firefox");
        break;

    default:
        System.out.println("Unknown Browser");
}
Enter fullscreen mode Exit fullscreen mode

Output

Google Chrome
Enter fullscreen mode Exit fullscreen mode

Common Beginner Mistakes

Forgetting break

Without break, execution falls through into the next case.


Using Variables in case

Incorrect

int value = 10;

case value:
Enter fullscreen mode Exit fullscreen mode

Only compile-time constants are allowed.


Using Unsupported Types

Incorrect

double price = 99.5;

switch (price) {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error.

Traditional switch does not support double.


Writing Statements Before the First case

Every executable statement must belong to a case or default.


Best Practices

  • Use switch when comparing one variable against many discrete values.
  • Always include a default case unless every possible value is handled.
  • Use break unless fall-through is intentional.
  • Group related cases together to avoid duplicate code.
  • Prefer meaningful enum names and string constants.

Quick Memory Trick 🧠

Remember the 4 C's of switch:

  • Compare one value.
  • Choose a matching case.
  • Continue until break.
  • Otherwise execute default.

Key Takeaways

  • switch improves readability when handling multiple fixed values.
  • Curly braces are mandatory.
  • case labels must be compile-time constants.
  • Duplicate case labels are not allowed.
  • Fall-through occurs when break is omitted.
  • default executes when no case matches.
  • Traditional switch supports primitives (byte, short, char, int), wrapper classes, enum, and String.
  • long, float, double, and boolean are not supported.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)