What is the difference between null
and the \"\"
(empty string)?
I have written some simple code:
String a = \"\";
String b
When you write
String a = "";
It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a
is holding a valid string object reference, all the methods of string can be applied here.
Whereas when you write
String b = null;
It means that there is a variable b
of type string which points to an unknown reference. And any operation on unknown reference will result in an NullPointerException
.
Now, let us evaluate the below expressions.
System.out.println(a == b); // false. because a and b both points to different object reference
System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.
System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed