5、switch语句能否作用在byte上,能否作用在long上,能否作用在String上?-Java面试题答案
/**
* 问题:switch语句能否作用在byte上,能否作用在long上,能否作用在String上
* 基本类型的包装类(如:Character、Byte、Short、Integer)
*
* switch可作用于char byte short int
* switch可作用于char byte short int对应的包装类
* switch不可作用于long double float boolean,包括他们的包装类
* switch中可以是字符串类型,String(jdk1.7之后才可以作用在string上)
* switch中可以是枚举类型
*/
switch可作用于char byte short int
switch可作用于char byte short int对应的包装类
switch不可作用于long double float boolean,包括他们的包装类,源代码示例:
package java基础题目; public class Test5 { 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); } }
package java基础题目; /* * switch中可以是字符串类型 *String(jdk1.7之后才可以作用在string上) */ public class Test6 { 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); } }
switch中可以是1.5枚举类型,源代码示例:
package java基础题目; /* * switch中可以是1.5枚举类型 */ //枚举三个量 enum Signal{ GREEN,YELLOW,RED; } public class Test7 { 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); } }