Java面试题:switch 是否能作用在byte上,是否能作用在long上,是否能作用在String上?
- switch 可作用于char byte short int
- switch 可作用于 char byte short int 对应的包装类
- switch 不可作用于 long double float boolean 包括他们的包装类
- switch 可作用于 String (jdk1.7 后才可以作用于String上)
- switch 可以是枚举类型(JDK1.5之后)
switch 只能是int 或 能转成int的 byte ,short ,char 。jdk 1.7 之后,string也可以。
在 switch (ecpr1)中,expr1 只能是一个整数表达式或者枚举常量,整数表达式可以是int 或 Integer 包装类型,由于 ,byte,short,char 都可以隐含转成 int ,所以这些类型以及它们的包装都可以作用在switch上。
显然,long 和 string 类型都不符合switch 的语法规定,并且不能被隐式转成int类型,所以它们不能作用于switch上。
另外 JDK1.7 中引入新特性,switch可以接收string类型的值,所以string自然也就可以作用在switch上。
原文链接: