字符串为空

public class TestNull {
 
 
 
public static void main(String[] args) {
 
String a = new String();
 
String b = "";
 
String c = null;
 
if (a.isEmpty()) {
 
System.out.println("String a = new String");
 
}
 
 
 
if (b.isEmpty()) {
 
System.out.println("String b = """);
 
}
 
 
 
if (c == null) {
 
System.out.println("String c = null");
 
}
 
 
 
if (null == a) {
 
System.out.println("String a = null");
 
}
 
 
 
if (a == "") {
 
System.out.println("a = ''");
 
}
 
 
 
if (a.equals("")) {
 
// 由于a是字符串,字符串的比较需要用equals,不能直接用 ==
 
System.out.println("a.equals("") is true");
 
}
 
 
 
/*if (c.isEmpty()) {
 
// 这里会报空指针,即null不能使用此方法
 
System.out.println("c == null and c.isEmpty");
 
}*/
 
 
 
List<String> list = new ArrayList<>();
 
// list.add("");
 
if (list.isEmpty()) {
 
System.out.println("list is empty");
 
}
 
System.out.println(list.size());
 
}
 
}

控制台输出:

分析:

此时a是分配了内存空间,但值为空,是绝对的空,是一种有值(值存在为空而已)。

此时b是分配了内存空间,值为空字符串,是相对的空,是一种有值(值存在为空字串)。

此时c是未分配内存空间,无值,是一种无值(值不存在)。

综上所述:

isEmpty() 分配了内存空间,值为空,是绝对的空,是一种有值(值 = 空)
"" 分配了内存空间,值为空字符串,是相对的空,是一种有值(值 = 空字串)
null 是未分配内存空间,无值,是一种无值(值不存在)

end

转自 https://blog.csdn.net/Echo_width/article/details/79653704

原文地址:https://www.cnblogs.com/shipengda/p/13924835.html