Java Switch Case Explained

Java switch case is a tool that selects a code block to execute based on the value of a given expression. It’s used to replace multiple if-else statements. Here’s how to do it.

Written by Abhinav Pandey
Published on Jun. 14, 2024
Developer coding in java on multiple screens
Image: Shutterstock / Built In
Brand Studio Logo

Java’s switch case is a powerful tool to replace multiple if-else statements. It is used to select one of the many code blocks to be executed based on the value of an expression.

What Is Java Switch Case?

Java switch case is used to select a code block to execute based on the value of a given expression. Once that expression is triggered, it executes the given code block. Switch case is used to replace multiple if-else statements.

Java 12 introduced switch expressions which improved the way we can write switch-case statements.

The switch-case statement has since been improved several times. Let’s take a look at the improvements and how to use the Java switch case statement.

 

Java Switch Case Syntax

Here’s the original syntax of a switch-case statement in Java

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    ...
    default:
        // code block
}

A switch-case statement can have multiple case blocks and an optional default block. The expression is evaluated and the matching case block is executed. If no case matches, the default block is executed.

In the original switch-case statement, each case block must end with a break statement to prevent fall-through to the next case block.

More on JavaA Guide to HashMap in Java With Examples

 

How to Use Java Switch Case

1. Arrow Case Expression

We can use the arrow case expression to simplify the case block. Only the statement appearing after the arrow will be executed if the case matches.

// NEW
switch (x) {
    case 1 -> System.out.println("One");
    case 2 -> System.out.println("Two");
    default -> throw new IllegalArgumentException();
}

This is similar to lambda syntax. If there were multiple statements, we could use a block instead.

// NEW (with block)
switch (x) {
    case 1 -> {
        System.out.println("One");
        System.out.println("One again");
    }
    case 2 -> System.out.println("Two");
    default -> System.out.println("Unknown");
}

Earlier, case blocks were required to end with a break statement. Otherwise, there would be a fall-through problem.

// OLD
switch (x) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
    default:
        System.out.println("Unknown");
}

2. Multiple Matching Values

What if a fall-through was desired? In the improved version of Java switch case, we can signal this with a comma separated list of values.

// NEW (multiple values)
switch (x) {
    case 1, 2:
        System.out.println("Valid values");
    default:
        System.out.println("Unknown");
}

In the old ways, we would have to write a separate case for each value and let it fall through to the last case which will contain the operations.

// OLD (fallthrough)
switch (x) {
    case 1:
    case 2:
        System.out.println("Valid values");
        break;
    default:
        System.out.println("Unknown");
}

3. Switch Expressions

A big improvement is that switch statements can be used to return a value, and therefore, can be used as expressions.

For example, we can use a switch-case block inline to print a value in words.

// switch expressions
System.out.println(switch (x) {
    case 1 -> "One";
    case 2 -> "Two";
    default -> "Unknown";
});

4. Yield Keyword

When a case has a single statement, as seen above, the value returned by the statement is returned by the switch expression. If the case has a block, we need to explicitly return the value using the yield keyword.

// switch expressions with yield
String word = switch (x) {
    case 1 -> {
        doSomething();
        yield "One";
    }
    case 2 -> "Two";
    default -> "Unknown";
};

Old-style case blocks can also be used in switch expressions and can have a yield statement. When using a yield statement, a break statement is not required. This is not recommended though. It's best to stick to the new style in order to avoid confusion and unexpected mistakes.

// old-style case blocks with yield
String word = switch (x) {
    case 1:         
        doSomething();
        yield "One";
    case 2: 
        yield "Two";
    default:
        yield "Unknown";
};

5. Exhaustiveness of Switch Expressions

Switch case statements are not required to be exhaustive. It is fine if no case matches and there is no default case. However, when using a switch to return a value, it is required that all cases are covered and one of them should always match.

For example, when implementing a switch on numbers, the default case can’t be left out:

// missing default case
String word = switch (x) {
    case 1 -> "One";
    case 2 -> "Two";
};

/* gives the error:
error: the switch expression does not cover all possible input values
      String word = switch (x) {
                    ^
*/

This means, we will always need to have a default case unless working with booleans.

The only exception to this is while using an enum and covering all possible enum values.

The below code works fine but it will give the same error as above if we remove one of the cases.

// switch expressions with enum
public class MyClass {
    static enum Color { RED, GREEN, BLUE };

    public static void main(String[] args) {
        Color color = Color.RED;
        System.out.println(switch (color) {
            case RED -> "Red";
            case GREEN -> "Green";
            case BLUE -> "Blue";
        });
    }
}

That's it for the improvements. One more feature worth mentioning is pattern matching but I have not covered it because it is still a preview feature.

An important point to note is that having an improved syntax doesn’t mean the old syntax is invalid now. Both syntaxes work.

A tutorial on how to use the Java switch case. | Video: Alex Lee

More on JavaWhat Is the Java Runtime Environment (JRE)?

 

Rules for Java Switch Case

As we have many new features in switch expressions, there are some rules to keep in mind while using them:

  • Arrow case expressions are less verbose as they don't require a break statement. They are less error-prone and easier to read.
  • When multiple values need to match with one case, use a comma-separated list of values instead of multiple case blocks.
  • When using a block in a case, use the yield keyword to return a value.
  • Always cover all possible cases when using switch expressions to return a value. If it isn’t possible to cover all possible values, use a default case.
  • If using an enum, we can skip the default case if all possible enum values are covered.
  • Finally, avoid mixing old-style and new-style case blocks in switch expressions to prevent confusion.

Frequently Asked Questions

Java’s switch case is a tool used to initiate one of many code blocks based on the value of a given expression. It can be used to replace multiple if-else statements.

The most common ways to use Java switch case include:

  1. Arrow case to simplify the case block.
  2. Signal a fall-through for multiple matching values with commas.
  3. Return a value with switch expressions
  4. Return a value when using a block with the yield keyword.
Explore Job Matches.