码迷,mamicode.com
首页 > 编程语言 > 详细

Java面试题:switch能否作用在byte、long、String上?

时间:2018-10-05 18:41:24      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   ted   static   byte   rap   sel   char   idg   wrapper   

  • 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能否作用在byte、long、String上?

标签:style   ted   static   byte   rap   sel   char   idg   wrapper   

原文地址:https://www.cnblogs.com/ls1617/p/9745134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!