What is the difference between null
and the \"\"
(empty string)?
I have written some simple code:
String a = \"\";
String b
What your statements are telling you is just that "" isn't the same as null - which is true. "" is an empty string; null means that no value has been assigned.
It might be more enlightening to try:
System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object
"" is still a string, meaning you can call its methods and get meaningful information. null is an empty variable - there's literally nothing there.
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 string null
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 a NullPointerException
at runtime.
This image might help you to understand the differences.
The image was collected from ProgrammerHumor
null
means nothing; it means you have never set a value for your variable but empty means you have set "" value to your String
for instance see the following example:
String str1;
String str2 = "";
Here str1
is null
meaning that you have defined it but not set any value for it yet, but you have defined str2
and set empty value for it so it has a value even that value is "";
but
String s=null;
String is not initialized for null. if any string operation tried it can throw null pointer exception
String t="null";
It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.
String u="";
It is as empty string , It will not throw null pointer.
null means the name isn't referencing any instantiated object. "" means an empty string.
Here a is referencing some object which happens to be an empty string. b isn't referencing any object as it's null.