Java面试题:switch能否作用在byte、long、String上?
2021-05-18 03:30
标签:style ted static byte rap sel char idg wrapper JDK1.5枚举 JDK1.7之后支持String,但是要求case也是String Java面试题:switch能否作用在byte、long、String上? 标签:style ted static byte rap sel char idg wrapper 原文地址:https://www.cnblogs.com/ls1617/p/9745134.html
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);
}
}
/*
* 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);
}
}
/*
* 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上?
文章链接:http://soscw.com/index.php/essay/87015.html