# Use Switch Expression

# Description

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

Requirements

  • Java 14

# 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());
}

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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