Java Switch String

2025年5月9日 | 阅读 3 分钟

Java 编程中有像 if-else 这样的条件语句,用于表示程序中的不同条件。但是,当条件数量较多时,使用 if-else 语句并不合适。为了解决这个问题,Java 编程语言自 JDK 7 版本起支持带字符串的 switch-case 语句。早期版本的 Java 只支持 enum 和 int 类型。

Java 中的 Switch case 语句

Switch case 语句提供了一种从不同的已定义条件中选择并执行特定条件的方法。

Switch 语句允许有多个可执行路径。Switch 语句可以处理不同的数据类型,如 byte、char、short 和 int。它还支持 enum 和 String 对象。

If-else 语句根据一系列可能的值来检查条件,而 switch 语句根据单个值来检查条件。

Switch case 语法

Java 中 switch 语句的示例

演示 switch 语句的 Java 程序。

SwitchExample.java

输出

Size of the shirt: Extra Large

上面的代码演示了在 Java 程序中使用 switch 语句。变量 numb 用作用户输入,根据定义的 case,衬衫的尺寸会显示在控制台上。

Java Switch Case 与 String

Java 编程使用 String 对象来实现各种条件语句。为了使用 String 实现条件,Java 在 JDK 7 版本中提供了带 String 的 switch case。

Java 中的带 String 的 switch case 通过移除多个 if-else 语句,使代码更具可读性。

Java 中的带 String 的 switch case 是区分大小写的。

由于 Java 中的带 String 的 switch case 使用 String.equals() 方法来比较用户传递的值和 case 值,因此必须添加 NULL 检查以避免 NullPointerException。

示例 1

演示带 String 的 switch case 的 Java 程序。

SwitchStringExample.java

输出

Black color identified
No color
Red color identified

在上面的 Java 代码中,switch 语句使用 case 的名称作为 String 字面量。不同的字符串 case 会将值返回给调用方法 getColor()

示例 2

演示多个 switch 条件的 Java 程序。

SwitchStringExample2.java

输出

Violet color identified
Orange color identified
No color identified

上面的 Java 代码实现了带有多个 case 的 Switch 语句。如果匹配到其中一个 case,它会在控制台上显示输出。

在本文中,我们讨论了 Java 中的 Switch 语句,switch 语句支持的不同数据类型,特别是 String。