# Use Switch Expression

# Description

In Java 14, the switch expressions (opens new window) turned to a standard feature. This rule replaces the traditional switch-case statements with switch-case expressions. Thus, avoiding the fall-through semantics of control flow and at the same time, removing some boilerplate code.

Requirements

  • Java 16

# Benefits

Removes code clutter. Improves readability.

# Tags

# Code Changes

# Initializing Variable

Pre

String medal;
switch(finished) {
case 1 : 
    medal = "Gold";
    break;
case 2: 
    medal = "Silver";
    break;
case 3: 
    medal = "Bronze";
    break;
default:
    medal = "None";
}

Post

String medal = switch (finished) {
    case 1 -> "Gold";
    case 2 -> "Silver";
    case 3 -> "Bronze";
    default -> "None";
};

# Computing the Returned Value

Pre

String findMedal(int finished) {
    switch(finished) {
    case 1 : 
        return "Gold";
    case 2: 
        return "Silver";
    case 3: 
        return "Bronze";
    default:
        return "None";
    }
}

Post

String findMedal(int finished) {
    return switch (finished) {
        case 1 -> "Gold";
        case 2 -> "Silver";
        case 3 -> "Bronze";
        default -> "None";
    };
}

# Labeled Cases Switch Statement

Pre

switch(finished) {
case 1 : 
    sendMedal("Gold", athlete);
    break;
case 2: 
    sendMedal("Silver", athlete);
    break;
case 3: 
    sendMedal("Bronze", athlete);
    break;
default:
    sendGratitude(athlete);
}

Post

switch (finished) {
    case 1 -> sendMedal("Gold", athlete);
    case 2 -> sendMedal("Silver", athlete);
    case 3 -> sendMedal("Bronze", athlete);
    default -> sendGratitude(athlete);
}

# Combine Switch Cases

Pre

switch(sport) {
case "diving":
case "swimming":
case "water polo": 
    cleanUpPool(now());
    break;
case "weightlifting":
case "gymnastic":
    cleanUpGym(now());
    break;
default: 
    cleanUpStadium(now());
}

Post

switch (sport) {
case "diving", "swimming", "water polo" -> cleanUpPool(now());
case "weightlifting", "gymnastic" -> cleanUpGym(now());
default -> cleanUpStadium(now());
}

You Want To Have Those Changes Done Automatically?

The automatic application of this rule is supported in the following jSparrow version:

# Properties

Property Value
Rule ID UseSwitchExpression
First seen in jSparrow version 4.3.0
Minimum Java version 14
Remediation cost 5 min