What is the difference between a null string (String s = null
) and an empty string (String s = ""
)?
This is what I have:
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
What does it mean?
So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.
The main difference between null and empty is that the null is used to refer to nothing while empty is used to refer to a unique string with zero length. A String refers to a sequence of characters.
Much like Zero, an Empty String ("") differs from a NULL value in that the former specifically implies that the value was set to be empty, whereas NULL means that the value was not supplied or is unknown. As an example, let's consider a column that stores a cell phone number.
In database terms, however, a null value is a value that doesn't exist: the field does not contain a value of any kind (not even a blank value). By contrast, a blank value is a real value: it just happens to be a string value containing 0 characters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With