下面是几个测试字符串是否为空示例:
1、使用 equals 方法
只需在空字符串字面调用 equals() 方法,并传递您要测试的对象即可,如下所示:
String nullString = null; String empty = new String();
boolean test = "".equals(empty); // true System.out.println(test); boolean check = "".equals(nullString); //false System.out.println(check);
|
在这种情况下,不会出现空指针错误,也不需要预先进行null检测。
2.使用 Apache Commons StringUtils 类
如果您已经在使用 Apache Commons,那么您也可以使用 isEmpty() 方法来检查 String 是否为空。这里唯一需要注意的是,该方法在输入为空的情况下也返回 true,这可能并不正确。true,这可能并不正确,这取决于您的应用程序对空字符串的定义。
如果您将 null 视为空字符串,那么您可以使用这个奇妙的 null-safe 方法进行快速测试,如下例所示:
boolean nullCheck = StringUtils.isEmpty(nullString); boolean emptyCheck = StringUtils.println(emptyCheck); ;// true
|
可以看出,对 null 字符串的检查与等价方法的行为相反。因此,请谨慎使用该方法。因为即使输入为空,它们也会返回 true,所以在进行 not null 和 empty 等测试时,我们不能相信它们。
3、检查 String 的长度是最快的方法
在 Java 中,有许多方法可以检查 String 是否为空、但什么才是正确的方法?
如果您不想使用第三方库,并且乐于自己进行空检查,那么检查 String 的长度是最快的方法,而使用 String 中的 isEmpty() 方法则是最具可读性的方法。
不要混淆空""字符串和 null 字符串,因为 null 不能被归类为空""字符串。
下面是使用 JDK 库本身检查字符串是否为空的三个示例。
public class StringEmptyTest {
public static void main(String args[]) {
String nonEmpty = "This is non Empty String"; String nullString = null; String emptyString = "";
// 在 Java 中使用 isEmpty() 方法检查字符串是否为空 // 需要预先进行 null 检查以避免 NullPointerException String[] inputs = {nonEmpty, nullString, emptyString}; for (String s : inputs) { if (s != null) { System.out.println(String.format("Does String '%s' is empty?", s) + s.isEmpty()); } }
// 使用 length() 方法检查字符串是否为空 // 对于空字符串 length() == 0,需要预先进行 null 检查 System.out.println("**** length() 方法示例 *****");
for (String s : inputs) { if (s != null) { System.out.println(String.format("Does String '%s' is empty?", s)+(s.length() == 0)); } }
// 使用 equals 方法检查字符串是否为空 // 这种方法是 null 安全的,不需要预先进行 null 检查 System.out.println("**** equals() 方法示例 *****"); for (String s : inputs) { System.out.println(String.format("Does String '%s' is empty?",s) +"".equals(s)); }
}
}
|
总结:
equals方法简单,不需要预先进行空null类型检测,因此天然避免了空指针报错;而其他两个办法只是对字符串内容为空""的检测,而无法实现对字符串类型从形式逻辑上进行检测。