码迷,mamicode.com
首页 > 其他好文 > 详细

isEmpty与null、""的区别

时间:2016-10-06 12:43:34      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

前一段时间我阅读别人的代码,发现有的时候用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.不管值是否分配内存空间都不会报错

isEmpty与null、""的区别

标签:

原文地址:http://www.cnblogs.com/tiantianfly/p/5933594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!