Difference between null and empty string
String s1 = "";
means that the empty String
is assigned to s1
.
In this case, s1.length()
is the same as "".length()
, which will yield 0
as expected.
String s2 = null;
means that (null
) or "no value at all" is assigned to s2
. So this one, s2.length()
is the same as null.length()
, which will yield a NullPointerException
as you can't call methods on null
variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
Null
means nothing. Its just a literal. Null
is the value of reference variable. But empty string is blank.It gives the length=0
. Empty string is a blank value,means the string does not have any thing.
No method can be invoked on a object which is assigned a NULL
value. It will give a nullPointerException
. Hence, s2.length()
is giving an exception.
When Object variables are initially used in a language like Java, they have absolutely no value at all - not zero, but literally no value - that is null
For instance: String s;
If you were to use s
, it would actually have a value of null
, because it holds absolute nothing.
An empty string, however, is a value - it is a string of no characters.
String s; //Inits to null
String a =""; //A blank string
Null
is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
Null
isn't really a value - and as such, doesn't have properties. So, calling anything that is meant to return a value - such as .length()
, will invariably return an error, because 'nothing' cannot have properties.
To go into more depth, by creating s1 = "";
you are initializing an object, which can have properties, and takes up relevant space in memory. By using s2;
you are designating that variable name to be a String, but are not actually assigning any value at that point.