Summary: 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.

上一篇:C puzzles详解【51-57题】


下一篇:NYOJ 1023 还是回文(DP,花最少费用形成回文串)