isEmpty與null、""的區別


前一段時間我閱讀別人的代碼,發現有的時候用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 code
26         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 location
36 //        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(),否則報空指針異常

2.isEmpty()不能分辨出值是空還是空字符串

null

1.null只能分辨出值是否不分配內存空間

“”

1.不管值是否分配內存空間都不會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM