java中switch case后接什么样的表达式呢
这是sun的官方解释:http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html
原文:" A switch
works with the byte
, short
, char
, and int
primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character
, Byte
, Short
, and Integer
(discussed in Simple Data Objects )."
说是switch case 可以接byte、short、char、int等基本类型,当然也可以接枚举及枚举的衍生类,和基本类型的包装类
Byte、Short、Character、Integer,这是截至到JDK1.6是这样的,到JDK1.7可以支持String这个特殊类型了
如果用到包装类的话,那么就得注意了,e.g:
switch(Character.valueOf('a')){
case Character.valueOf('a'):
System.out.println("==");break;
}
或者是这样的:
switch('a'){
case Character.valueOf('a'):
System.out.println("==");break;
}
这样是错误的,case 后的表达式必须是final的常量类型