Skip to content

Latest commit

 

History

History
77 lines (64 loc) · 1.66 KB

File metadata and controls

77 lines (64 loc) · 1.66 KB

Switch Case

  • Beginning with JDK 14, switch has addition of four new features
    1. The switch expression
    2. The yield statement
    3. Support for a list of case constants
    4. The case with an arrow

Traditional Switch Case

class Error{
    
    public static int getPriorityLevel(int errorCode){
        int priorityLevel;
        
        switch(errorCode){
            case 1000:
            case 1500:
            case 2000:
            case 2500:
                priorityLevel = 1;
                break;
            case 3000:
            case 3500:
                priorityLevel = 2;
                break;
            case 500:
            case 800:
                priorityLevel = 3;
                break;
            default:
                priorityLevel = 0;
        }
        
        return priorityLevel;
    }
}

using switch expression, case constants and yield

class Error{
    public static int getPriorityLevel(int errorCode){
        
        int priorityLevel = switch(errorCode){
            case 1000, 1500, 2000, 2500: // using case constants
                yield 1; // immediately terminates switch
            case 3000, 3500:
                yield 2;
            case 500, 800:
                yield 3;
            default:
                yield 0;
        };
        
        return priorityLevel;
    }
}

using case with an arrow

class Error{
    public static int getPriorityLevel(int errorCode){
        return switch (errorCode) {
            case 1000, 1500, 2000, 2500 -> 1;
            case 3000, 3500 -> 2;
            case 500, 800 -> 3;
            default -> 0;
        };
    }
}