/**
测试环境JDK1.8
1.byte,short在使用switch语句的时候都可以默认转换为int型
2.char也能被switch语句支持
3.String也能被switch语句支持
4.boolean不被switch语句支持,因为不能转换为int类型,一般用if...else...语句代替
5.long,float,double不被switch语句支持,除非强制转换为int类型,
但是数据有可能丢失,一般用if...else...语句代替
6.其它类对象需要用到switch语句的话,首先要根据需要重写toString()方法,然后在switch(表达式)
表达式必须调用toString()方法转换为字符串形式
*/
public class Test21 {
public static void main(String[] args) {
byte b = 2 ;
char c = 'c';
short s = 2 ;
int i = 2 ;
boolean bl = false ;
String str = "hello";
long l = 2L ;
float f = 2.14f ;
double d = 1.44d ;
//byte型
switch(b){
case 1:System.out.println("byte=1 case");
break;
case 2:System.out.println("byte=2 case");
break;
}
//char型
switch(c){
case 'a':System.out.println("char='a' case");
break;
case 'b':System.out.println("char='b' case");
break;
case 'c':System.out.println("char='c' case");
break;
}
//short型
switch(s){
case 1:System.out.println("short=1 case");
break;
case 2:System.out.println("short=2 case");
break;
}
//int型
switch(i){
case 1:System.out.println("int=1 case");
break;
case 2:System.out.println("int=2 case");
break;
}
//布尔型不能转换为int,一般用if...else...语句代替
/*
switch(bl){
case true:System.out.println("boolean=true case");
break;
case false:System.out.println("byte=false case");
break;
}
*/
//String字符串型
switch(str){
case "bye":System.out.println("string=\"bye\" case");
break;
case "hello":System.out.println("string=\"hello\" case");
break;
}
//long,float,double必须强制转换为int型才能用switch语句
/*
switch((int)l){
case 1:System.out.println("long=1 case");
break;
case 2:System.out.println("long=2 case");
break;
}
switch((int)f){
case 1:System.out.println("float=1 case");
break;
case 2:System.out.println("float=2 case");
break;
}
switch((int)d){
case 1:System.out.println("double=1 case");
break;
case 2:System.out.println("double=2 case");
break;
}
*/
TestSwitch ts = new TestSwitch("object");
//对象型
switch(ts.toString()){
case "class":System.out.println("object = \"class\" case");
break;
case "object":System.out.println("object = \"object\" case");
break;
}
System.out.println("程序结束!");
}
}
/*
测试switch语句接收对象
*/
class TestSwitch{
private String name;
TestSwitch(String name){
this.name = name;
}
public String toString(){
return name;
}
}
运行结果:
byte=2 case
char='c' case
short=2 case
int=2 case
string="hello" case
object = "object" case
程序结束!