Jack said:
Which of the following ways is better to initialize a string?
String str = null;
and
String str = "";
The first way may cause NullPointerException.
Thanks.
The first way won't cause an NPE any more than the second one will,
since in both cases it'll be a logic error that really causes the
exception. IOW, a logic error with the first case may cause you to
invoke a String method before you assign an object reference to "str",
but in the second case you might set the variable to null before
invoking a method.
The two cases are different. The first case comes about typically
because you need to initialize the String variable (it's a local
variable, say) but you have not yet got a reasonable default to assign
to it (often because of scopes). It's often a mistake to assign it a
default of "" because (1) that probably isn't a reasonable value, and
(2) you've now set yourself up for a whole class of logical errors. With
respect to the latter point, what I mean by that is, now invoking a
String method will succeed, because you've got the value of "", but
you're scratching your head wondering why the results are so whacked,
because you're sure you didn't "really" initialize the variable yet.
This is anecdotal, but I personally almost never have cause to use case #2.
AHS