Is a switch executing all the cases without stopping?

后端 未结 3 540
滥情空心
滥情空心 2020-12-20 01:31

I\'m on Java 8v60. I tried to embed a switch regarding an exception group in a catch block. Apparently, the case are recognised, but once they get into the switch, they keep

3条回答
  •  悲&欢浪女
    2020-12-20 01:54

    The switch statements jump to the right value, and continue up to the end of other cases.

    If you like to exit the switch statement you have to use a break (or return in some situations).

    This is useful to handle situations in wich many values can be handled at the same manner:

    switch (x) {
        case 0:
        case 1:
        case 2:
            System.out.println("X is smaller than 3");
            break;
        case 3:
            System.out.println("X is 3");
        case 4:
            System.out.println("X is 3 or 4");
            break;
    }
    

    If the case selection is also a final condition for a method you can return from it.

    public String checkX(int x) {
        switch (x) {
        case 0:
        case 1:
        case 2:
            return "X is smaller than 3";
        case 3:
            return "X is 3";
        case 4:
            return ("X is necessary 4");
        default:
            return null;
    
        }
    }
    
    
    
    }
    

提交回复
热议问题