Search code examples
javaconditional-statementspreferencesvariable-initialization

Java String initialization


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.


Solution

  • 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.