isEmpty與null、""的區別,isemptynull區別
前一段時間我閱讀別人的代碼,發現有的時候用isEmpty,有的時候用null,有的時候用""。我很困惑三者之間的區別,於是我就自己寫了一個程式來驗證一下
1 public class Test { 2 public static void main(String[] args) { 3 //分配記憶體空間,值為空白 4 String a = new String(); 5 //分配記憶體空間,值為空白字串 6 String b = ""; 7 //未分配記憶體空間 8 String c = null; 9 10 if (a != null) {11 System.out.println("a值存在");12 }13 if (b != null) {14 System.out.println("b值存在");15 }16 if (c == null) {17 System.out.println("c值不存在");18 }19 if (a == "") {20 System.out.println("a值存在,為空白字串");21 }22 if (b == "") {23 System.out.println("b值存在,為空白字串");24 }25 //dead code26 if (c == "") {27 System.out.println("c值存在,為空白字串");28 }29 if (a.isEmpty()) {30 System.out.println("a值存在,為空白字串或者為空白");31 }32 if (b.isEmpty()) {33 System.out.println("b值存在,為空白字串或者為空白");34 }35 // Null pointer access: The variable c can only be null at this location36 // if (c.isEmpty()) {37 // System.out.println("String c=null");38 // }39 }40 41 }View Code
啟動並執行結果如下
1 a值存在2 b值存在3 c值不存在4 b值存在,為空白字串5 a值存在,為空白字串或者為空白6 b值存在,為空白字串或者為空白View Code
得出的結論:
isEmpty()
1.如果不分配記憶體空間,不能用isEmpty(),否則報null 指標異常
2.isEmpty()不能分辨出值是空還是Null 字元串
null
1.null只能分辨出值是否不分配記憶體空間
“”
1.不管值是否分配記憶體空間都不會報錯