Difference between null and empty ("") Java String Difference between null and empty ("") Java String java java

Difference between null and empty ("") Java String


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

Difference between null and 0/empty string

Original image by R. Sato (@raysato)


"" 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.


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