isEmpty與null、""的區別,isemptynull區別

來源:互聯網
上載者:User

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.不管值是否分配記憶體空間都不會報錯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.