结合空值和空字符串检查
在上一步中,我们学习了如何使用 ==
运算符检查变量是否为 null
。然而,在 Java 中,尤其是处理 String
对象时,通常不仅需要检查变量是否为 null
,还需要检查它是否“为空”。空字符串是一个存在但不包含任何字符的 String
对象(例如 ""
)。而 null
字符串则表示该变量根本不引用任何 String
对象。
尝试对 null
字符串调用 isEmpty()
或 length()
等方法会导致 NullPointerException
。因此,当你想以相同的方式处理 null
字符串和空字符串时(例如,将它们视为“空白”或“缺失”),就需要同时检查这两种情况。
最常见的做法是先检查字符串是否为 null
,如果不是 null
,再使用 isEmpty()
方法检查它是否为空。
让我们修改 HelloJava.java
程序来演示如何结合这些检查。
-
在 WebIDE 编辑器中打开 HelloJava.java
文件。
-
将当前代码替换为以下内容:
public class HelloJava {
public static void main(String[] args) {
String text1 = null;
String text2 = ""; // An empty string
String text3 = "Hello"; // A non-empty string
System.out.println("Checking text1 (null):");
if (text1 == null || text1.isEmpty()) {
System.out.println("text1 is null or empty.");
} else {
System.out.println("text1 is not null and not empty: " + text1);
}
System.out.println("\nChecking text2 (empty):");
// It's crucial to check for null first!
if (text2 == null || text2.isEmpty()) {
System.out.println("text2 is null or empty.");
} else {
System.out.println("text2 is not null and not empty: " + text2);
}
System.out.println("\nChecking text3 (not empty):");
if (text3 == null || text3.isEmpty()) {
System.out.println("text3 is null or empty.");
} else {
System.out.println("text3 is not null and not empty: " + text3);
}
}
}
在这个更新后的代码中:
- 我们引入了三个
String
变量:text1
(null
)、text2
(空字符串)和 text3
(非空字符串)。
- 我们使用逻辑或运算符 (
||
) 来结合 null
检查 (text == null
) 和空字符串检查 (text.isEmpty()
)。
- 条件
text == null || text.isEmpty()
在 text
为 null
或者 text
不为 null
且 text.isEmpty()
为 true
时为 true
。
- 重要提示:
null
检查 (text == null
) 必须在 ||
条件中排在首位。如果 text
为 null
,||
条件的第一部分 (text == null
) 为 true
,Java 会使用“短路求值”跳过第二部分 (text.isEmpty()
),从而避免 NullPointerException
。如果 isEmpty()
检查排在首位且 text
为 null
,则会导致错误。
-
保存文件(Ctrl+S 或 Cmd+S)。
-
在终端中编译程序:
javac HelloJava.java
-
运行程序:
java HelloJava
你应该会看到以下输出:
Checking text1 (null):
text1 is null or empty.
Checking text2 (empty):
text2 is null or empty.
Checking text3 (not empty):
text3 is not null and not empty: Hello
这个输出表明,我们的组合检查正确地将 null
字符串 (text1
) 和空字符串 (text2
) 识别为“null
或为空”,同时也正确地识别出了非空字符串 (text3
)。
这种组合检查 (string == null || string.isEmpty()
) 是 Java 中处理 null
字符串和空字符串时非常常见的模式。许多库也为此提供了实用方法,例如 Apache Commons Lang 中的 StringUtils.isEmpty()
或 StringUtils.isBlank()
(还会检查是否为空白字符),但理解基本的组合检查是基础。