Difference between null and empty ("") Java String
Solution 1:
You may also understand the difference between null and an empty string this way:
Original image by R. Sato (@raysato)
Solution 2:
"" 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
String a = new String("");
String b = new String("");
System.out.println(a==b);
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, because equals
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.
String a = "abc";
String b = "abc";
System.out.println(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.