Java面试题:switch能否作用在bytelongString上?

Posted ls1617

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java面试题:switch能否作用在bytelongString上?相关的知识,希望对你有一定的参考价值。

  • switch可作用于char byte short int

  • switch可作用于char byte short int对应的包装类

  • switch不可作用于long double float boolean,包括他们的包装类

  • switch中可以是字符串类型,String(JDK1.7之后才可以作用在string上)

  • switch中可以是枚举类型(JDK1.5之后)

public class Test {
    public static void main(String[] args) {
        // switch可作用于char byte short int
        char season1 = 3;
        byte season2 = 3;
        short season3 = 3;
        int season4 = 3;
 
        // switch可作用于char byte short int对应的包装类
        Character season11 = 3;
        Byte season22 = 3;
        Short season33 = 3;
        Integer season44 = 3;
 
        // 下面的基本类型的包装类就不行了,还有double float的包装类
        // Long season = 0;
 
        // switch不可作用于long double float boolean,包括他们的包装类
        long season5 = 3;
        double season6 = 3;
        float season7 = 3f;
        boolean season8 = false;
 
        String strSeason = "";
        switch (season1) {
        case 1:
            strSeason = "Spring";
            break;
        case 2:
            strSeason = "Summer";
            break;
        case 3:
            strSeason = "Fall";
            break;
        case 4:
            strSeason = "Winter";
            break;
        default:
            strSeason = "四季中没有这个季节";
            break;
        }
        System.out.println("strSeason:" + strSeason);
    }
}

JDK1.5枚举

/*
 * switch中可以是1.5枚举类型
 */
//枚举三个量
enum Signal{
    GREEN,YELLOW,RED;
}
public class Test {
    public static void main(String[] args) {
        Signal color = Signal.RED;
        
        switch (color) {
        case RED:
            color = Signal.YELLOW;
            break;
        case YELLOW:
            color = Signal.RED;
        case GREEN:
            color = Signal.YELLOW;
        default:
            System.out.println("什么鬼灯");
            break;
        }
        
        System.out.println("color:"+color);
    }
}

JDK1.7之后支持String,但是要求case也是String

/*
 * switch中可以是字符串类型
 *String(jdk1.7之后才可以作用在string上)
 */
public class Test {
    public static void main(String[] args) {
        int season = 0;
        String strSeason = "Summer";
        switch (strSeason.toLowerCase()) {
        case "spring":
            season = 1;
            break;
        case "summer":
            season = 2;
            break;
        case "fall":
            season = 3;
            break;
        case "winter":
            season = 4;
            break;
        default:
            season = -1;// 没找到对应的季节
            break;
        }
        System.out.println(strSeason + "-->" + season);
    }
}

以上是关于Java面试题:switch能否作用在bytelongString上?的主要内容,如果未能解决你的问题,请参考以下文章

Java面试题03

java面试题03

java面试题03

每日十个面试题--(java基础篇)-(1-10)

android遇到的一些经典面试题

Java面试题整理