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