null 和空(“")Java String 的区别 [英] Difference between null and empty ("") Java String

查看:30
本文介绍了null 和空(“")Java String 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

null""(空字符串)有什么区别?

What is the difference between null and the "" (empty string)?

我写了一些简单的代码:

I have written some simple code:

String a = "";
String b = null;

System.out.println(a == b); // false
System.out.println(a.equals(b)); // false

两个语句都返回 false.看来,我无法找到它们之间的实际区别.

Both statements return false. It seems, I am not able to find what is the actual difference between them.

推荐答案

"" 是一个实际的字符串,尽管是一个空字符串.

"" is an actual string, albeit an empty one.

然而,null 意味着 String 变量不指向任何内容.

null, however, means that the String variable points to nothing.

a==b 返回 false,因为 "" 和 null 在内存中不占用相同的空间——换句话说,它们的变量不指向相同的对象.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) 返回 false,因为"显然不等于 null.

a.equals(b) returns false because "" does not equal null, obviously.

不同之处在于,因为 "" 是一个实际的字符串,你仍然可以像这样调用方法或函数

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

等等.

如果字符串等于 null,比如 b,如果你尝试调用,Java 会抛出一个 NullPointerException,比如:

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()

如果您想知道 == 和 equals 的区别,那就是:

If the difference you are wondering about is == versus equals, it's this:

== 比较引用,就像我去了

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

那会输出 false 因为我分配了两个不同的对象,并且 a 和 b 指向不同的对象.

That would output false because I allocated two different objects, and a and b point to different objects.

然而,在这种情况下 a.equals(b) 将返回 true,因为字符串的 equals 将返回 true 当且仅当参数 String 不为空且表示相同的字符序列时.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

但是请注意,Java 确实对字符串有特殊情况.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

你会认为输出是 false,因为它应该分配两个不同的字符串.实际上,Java 将intern 文字字符串(那些在我们的示例中像 a 和 b 一样初始化).所以要小心,因为这可能会给 == 的工作方式带来一些误报.

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

这篇关于null 和空(“")Java String 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆