1 switch 语句与整数类型
switch
语句支持 char
以及 byte
、short
和 int
等整数类型(包括其所对应的包装类型),但是并不支持 long
类型以及float
和 double
等浮点类型。其根本原因在于 switch
语句的底层 lookupswitch
和 tableswitch
只支持 int
类型(char
、byte
、short
可以隐式的转换成 int
),long
、float
和 double
等类型在转换成 int
类型时可能会丢失精度。
package com.hcong.control;
/**
* @Classname testSwitch
* @Date 2023/3/27 18:22
* @Created by HCong
*/
public class testSwitch {
public static void main(String[] args) {
testByte((byte) 0);
testShort((short) -32769);
testInt(0);
}
/**
* 表达式的类型为:byte
*
* @param number
*/
public static void testByte(byte number) {
switch (number) {
case -128:
System.out.println("byte -128");
break;
case 0:
System.out.println("byte 0");
break;
default:
System.out.println("byte 127");
}
}
/**
* 表达式的类型为:short
*
* @param number
*/
public static void testShort(short number) {
switch (number) {
case -32768:
System.out.println("short -32768");
break;
case 0:
System.out.println("short 0");
break;
default:
System.out.println("short 32767");
}
}
/**
* 表达式的类型为:int
*
* @param number
*/
public static void testInt(int number) {
switch (number) {
case Integer.MIN_VALUE:
System.out.println("int " + Integer.MIN_VALUE);
break;
case 0:
System.out.println("int 0");
break;
default:
System.out.println("int " + Integer.MAX_VALUE);
}
}
}
2 switch 语句与字符串类型
Java 7 之后 switch
语句可以使用 String
类型,其原因在于不同字符串所生成的 hashcode
并不相同,而 hashcode
的取值范围与 int
类型的取值范围保持一致。
package com.hcong.control;
/**
* @Classname testSwitch
* @Date 2023/3/27 18:22
* @Created by HCong
*/
public class testSwitch {
public static void main(String[] args) {
testString("start");
}
/**
* 表达式的类型为:string
*
* @param str
*/
public static void testString(String str) {
// 比较字符串的 hashcode
switch (str) {
case "start":
System.out.println("String start");
break;
case "Hello World":
System.out.println("String Hello World");
break;
default:
System.out.println("String end");
}
}
}
3 switch 语句与枚举类型
枚举类型建立了常量值与名字的关联,并且枚举类型的取值为整数,故而可以在 switch
中使用。
package com.hcong.control;
/**
* @Classname testSwitch
* @Date 2023/3/27 18:22
* @Created by HCong
*/
public class testSwitch {
public static void main(String[] args) {
testEnum(enumDouble.NUM_ONE);
}
/**
* 表达式的类型为:enum
*
* @param enu
*/
public static void testEnum(enumDouble enu) {
switch (enu) {
case NUM_ONE:
System.out.println("NUM_ONE");
break;
case NUM_TWO:
System.out.println("NUM_TWO");
break;
case NUM_THREE:
System.out.println("NUM_THREE");
break;
default:
System.out.println("NUM_FOUR");
}
}
}
enum enumDouble {
NUM_ONE,
NUM_TWO,
NUM_THREE,
NUM_FOUR
}