欢迎访问我的个人博客。
本文主要介绍String为空的几种形式,以及空值判断方式的区别。
1. new String、null和“”区别
根据一段代码来比较String不同状态的“空”:
public static void main(String[] args) {
String a = null;
String b = "";
String c = new String();
test(a);
//test(b);
//test(c);
}
public static void test(String string) {
if (string == null) {
System.out.println("string == null");
}
if ("".equals(string)) {
System.out.println("string 为 '' ");
}
if (string.isEmpty()) {
System.out.println("string 为 empty");
}
}
执行test(a)的结果是:
string == null
Exception in thread "main" java.lang.NullPointerException
说明String为null时使用isEmpty()方法会报空指针异常!
查看该方法的源码可以发现原因是:
public boolean isEmpty() {
return value.length == 0;
}
value的本质又是什么呢?
private final char value[];
是定义了的一个数组。所以此时的value是不能为null的。
执行test(b)和test©都是一样的结果:
string 为 ''
string 为 empty
由此我们可以分析:
a. 给String赋值null,本质是没有给它开辟内存空间,它的空指的是不存在。
b. 给String赋值“”,是给它分配了内存空间的,实际上是有值,存储的是“空字符串”。
c. new String的时候,也是分配了内存空间,只不过此时这片空间没有放东西,此时的空指的是“空值”。
所以我们要谨慎使用String.isEmpty()方法, 防止在判断的值为null时会报空指针异常 。
判断字符串是否为空有一个更美妙的方法就是使用StringUtils类。
2. org.apache.commons.lang.StringUtils
StringUtils中isEmpty()和isBlank()区别:
isEmpty()判断某字符串是否为空,为空的标准是 str==null 或 str.length()====0 :
// Empty checks
// Checks if a String is empty ("") or null.
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
看源码一目了然:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
isBlank()判断某字符串是否为空或长度为0或空白符(whitespace)构成:
//Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
看一下源码(对空白符做了判断):
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
参考文章: