What is the difference between a null string (
String s = null
String s = ""
String s1 = ""; //print statement does not print any thing for s1 but s1.length()=0
String s2 = null;//print statement prints "null" for s2 but s2.length() gives exception
String s1 = ""; means that the empty
String is assigned to
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
Actually has the same effect as:
String s1 = null;
String s1 = "";
Is, as said, a different thing.