Search code examples
javaswitch-statement

Multiple switch statement using advance/new type


enter image description here

I am trying to use this format for the switch statement but getting error in Eclipse, but somehow it is not throwing an error in IntelliJ. What needs to be changed?

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int switchValue = 3;
    
    switch(switchValue) {
    case 1: System.out.println("Value was 1");
    case 2: System.out.println("Value was 2");
    case 3,4,5 ->
    {
        System.out.println("Value was 3");
    }
    
    default -> System.out.println("Was not 1,2,3,4 or 5");
    }
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Mixing of different kinds of case statements '->' and  ':' is not allowed within a switch

    at keywords.Switchhh.main(Switchhh.java:12)

Solution

  • Note that although according to Eclipse, you can't mix case statement types in the same switch block, you can mix the two switch block types as long as they are completely separated within the code. The following works in Eclipse (Version: 2024-03 (4.31.0)) (although I can't think of a reason to do it).

    switch (switchValue) {
        case 1:
            System.out.println("Value was 1");
            break;
        case 2:
            System.out.println("Value was 2");
            break;
        default : {
            switch (switchValue) {
                case 1, 2, 3 -> System.out.println("Value was 3");
                default -> System.out.println("Was not 1,2,3,4 or 5");
            }
        }
    }