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.
"" is an actual string, albeit an empty one.
null, however, means that the String variable points to nothing.
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)
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)
and so on.
If the String equals null, like b, Java would throw a
NullPointerException
if you tried invoking, say:b.length()
If the difference you are wondering about is == versus equals, it's this:
== compares references, like if I went
That would output false because I allocated two different objects, and a and b point to different objects.
However,
a.equals(b)
in this case would return true, becauseequals
for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.Be warned, though, that Java does have a special case for Strings.
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.