Java 中isEmpty和null、"" 的区别

Java 中String中的""null和isEmpty的区别到底是什么?

public class demo {
    public static void main(String[] args) {
        String str = new String();
        String str1 = "";
        String str2 = null;
        if (str.isEmpty()) {
            System.out.println("str的值为空");
        }
        if(str1.isEmpty()){
            System.out.println("str1的值为空");
        }
        if (str == null){
            System.out.println("str == null");
        }
        if (str1 == null){
            System.out.println("str1 == null");
        }
        if (str2 == null){
            System.out.println("str2 == null");
        }
    }
}

在这里插入图片描述
通过上面的代码我们能够发现,new String()、空串和null是不一样的,那它们的区别在哪?别急,看下面。

1、Str是分配了内存空间,但值为空,是绝对的空,是一种有值(值存在为空而已)。
2、str1是分配了内存空间,值为空字符串,是相对的空,是一种有值(值存在为空字串)。
3、str2是未分配内存空间,无值,是一种无值(值不存在)
发布了58 篇原创文章 · 获赞 7 · 访问量 2295

猜你喜欢

转载自blog.csdn.net/weixin_42492089/article/details/103079257