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.
From the wikipedia article on empty string.
A string can be empty or have a
null
value. If a string isnull
, it isn't referring to anything in memory. Trys.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 asnull
. Whereas if you check for length, then it will exit out of it's loop.You may also understand the difference between null and empty string this way:
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
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 assignednull
it means there is no underlying object of any kind, string or otherwise.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 stringnull
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 aNullPointerException
at runtime.