Why can't I use switch statement on a String?

前端 未结 16 2029
面向向阳花
面向向阳花 2020-11-21 07:57

Is this functionality going to be put into a later Java version?

Can someone explain why I can\'t do this, as in, the technical way Java\'s switch state

16条回答
  •  不知归路
    2020-11-21 08:17

    In Java 11+ it's possible with variables too. The only condition is it must be a constant.

    For Example:

    final String LEFT = "left";
    final String RIGHT = "right";
    final String UP = "up";
    final String DOWN = "down";
    
    String var = ...;
    
    switch (var) {
        case LEFT:
        case RIGHT:
        case DOWN:
        default:
            return 0;
    }
    

    PS. I've not tried this with earlier jdks. So please update the answer if it's supported there too.

提交回复
热议问题