随笔 - 301  文章 - 2  评论 - 16  阅读 - 34万

Java中的isEmpty方法、null以及""的区别

复制代码
public class TestNull {
 
    public static void main(String[] args) {
        String a = new String();
        String b = "";
        String c = null;
        if (a.isEmpty()) {
            System.out.println("String a = new String");
        }
 
        if (b.isEmpty()) {
            System.out.println("String b = \"\"");
        }
 
        if (c == null) {
            System.out.println("String c =null");
        }
 
        if (null == a) {
            System.out.println("String a =null");
        }
 
        if (a == "") {
            System.out.println("a = ''");
        }
    }
}
复制代码

控制台输出:

 

分析:

此时a是分配了内存空间,但值为空,是绝对的空,是一种有值(值存在为空而已)。

此时b是分配了内存空间,值为空字符串,是相对的空,是一种有值(值存在为空字串)。

此时c是未分配内存空间,无值,是一种无值(值不存在)。

 

综上所述:

isEmpty() 分配了内存空间,值为空,是绝对的空,是一种有值(值 = 空)
"" 分配了内存空间,值为空字符串,是相对的空,是一种有值(值 = 空字串)
null 是未分配内存空间,无值,是一种无值(值不存在)

 

例子二: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    public static void main(String[] args) {
        String a = new String();
        String b = "";
        String c = null;
        if (a.isEmpty()) {
            System.out.println("String a is empty");
        }
        if (b.isEmpty()) {
            System.out.println("String b is empty");
        }
        if (c == null) {
            System.out.println("String c = null");
        }
        if (null == a) {
            // 编译器直接就提示了Dead code,a指向了一个新对象,肯定不是null了
            System.out.println("String a =null");
        }
        if (a == "") {
            System.out.println("a = ''");
        }
        if (a.equals("")) {
            //由于a是字符串,字符串的比较需要用equals,不能直接用 ==
            System.out.println("a = ''");
        }
        /*if (c.isEmpty()) {
            // 这里会报空指针,即null不能使用此方法
            System.out.println("c == null   and   c.isEmpty");
        }*/
         
        List<String> list = new ArrayList<>();
        //list.add("");
        if (list.isEmpty()) {
            System.out.println("list is empty");
        }
        System.out.println(list.size());
    }
/*Output:
String a is empty
String b is empty
String c = null
equals:a = ''
list is empty
0
*/

end
原文链接:https://blog.csdn.net/peng86788/article/details/80885814

posted on   Code2020  阅读(825)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示