Difference between null and empty (“”) Java String

2018-12-31 23:41发布

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

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

13条回答
十年一品温如言
2楼-- · 2019-01-01 00:03

The empty string is distinct from a null reference in that in an object-oriented programming language a null reference to a string type doesn't point to a string object and will cause an error were one to try to perform any operation on it. The empty string is still a string upon which string operations may be attempted.

From the wikipedia article on empty string.

查看更多
人间绝色
3楼-- · 2019-01-01 00:03

A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.

查看更多
流年柔荑漫光年
4楼-- · 2019-01-01 00:05

You may also understand the difference between null and empty string this way:

Difference between null and 0/empty string

查看更多
怪性笑人.
5楼-- · 2019-01-01 00:06

String is an Object and can be null

null means that the String Object was not instantiated

"" is an actual value of the instantiated Object String like "aaa"

Here is a link that might clarify that point http://download.oracle.com/javase/tutorial/java/concepts/object.html

查看更多
大哥的爱人
6楼-- · 2019-01-01 00:07

In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 00:08

There is a pretty significant difference between the two. The empty string "" is "the string that has no characters in it." It's an actual string that has a well-defined length. All of the standard string operations are well-defined on the empty string - you can convert it to lower case, look up the index of some character in it, etc. The null string null is "no string at all." It doesn't have a length because it's not a string at all. Trying to apply any standard string operation to the null string will cause a NullPointerException at runtime.

查看更多
登录 后发表回答