首页 > 代码库 > Difference between null and empty String

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(), witch will yield 0 as expected.

String s2 = null; means that (null) or "no value at all" is assigned to s2. To this one,s2.length() is the same as null.length(), witch will yield a NullPointerException as you can‘t call methods on null variables (pointers, sort of) on 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.

Difference between null and empty String