本文概述
- Switch语句示例1中的字符串
- Switch语句示例2中的字符串
它只能是字符串对象。
Object game = "Hockey";
// It is not allowed
String game = "Hockey";
// It is OK.
字符串对象区分大小写。
"Hickey" and "hocker" are not equal.
没有空对象
传递字符串对象时要小心, 将null对象的原因传递给NullPointerException。
Switch语句示例1中的字符串
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Cricket";
switch(game){
case "Hockey":
System.out.println("Let's play Hockey");
break;
case "Cricket":
System.out.println("Let's play Cricket");
break;
case "Football":
System.out.println("Let's play Football");
}
}
}
输出:
Let's play Cricket
Switch语句示例2中的字符串
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Card-Games";
switch(game){
case "Hockey": case"Cricket": case"Football":
System.out.println("This is a outdoor game");
break;
case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
System.out.println("This is a indoor game");
break;
default:
System.out.println("What game it is?");
}
}
}
【Switch语句中的字符串】输出:
This is a indoor game
推荐阅读
- Win7/Win8/win10系统删除右键菜单“CMD迅速通道”选项的办法
- Java StringJoiner
- 带下划线的Java数字字面量
- Java Heredocs用法实例
- Java Lambda表达式
- Java默认方法
- Java二进制字面量
- Java注解类型
- Java 9接口private方法