字串為空
阿新 • • 發佈:2020-11-04
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