Java String initialization

ewa picture ewa · Jul 23, 2010 · Viewed 14.9k times · Source

Which do you prefer and why"

String myString = null;
if(someCondition)
   myString = "something";
else
   myString = "something else";

OR

String myString = "";
if(someCondition)
   myString = "something";
else
   myString = "something else";

I know that using the ternary (? :) operator is possible but I'd like to know about the above two.

Answer

Jon Skeet picture Jon Skeet · Jul 23, 2010

Neither. Instead, this:

String myString;
if (someCondition)
   myString = "something";
else
   myString = "something else";

In both of your alternatives, the variable is initialized with a value which will never ever be read. The fact that it's present at all is misleading.

I would actually use the conditional operator, of course - but barring that, the above is the better option.