The idiomatic way is to use ternary/conditional operator (JLS 15.25):
String myString = (someCondition ? "something" : "something else");
But you can also do the more verbose if-else statement if you really feel you must:
final String myString;
if(someCondition) {
myString = "something";
} else {
myString = "something else";
}
Note that I've added final modifier in the above snippet. If you're planning on further reassignments to the variable, then of course it can't be final, so you can remove the modifier and of course the code would still work.
Why final?
The point of the final in the above snippet is to show that the if-else construct will assign to myString once and exactly once in all possible execution paths. That is the main idea of the proposed if-else solution: if you're going to assign a value to a local variable only once, even if it can be one of several possibilities, then make it final to enhance readability.
Contrast that with this "alternative" proposal for example:
// DON'T DO THIS! Example only!
String myString = "something else";
if (someCondition) myString = "something";
With this construct, you may be assigning to myString twice, thus you couldn't put final here even if there was no further reassignment. You also couldn't put final in either of the original = null; or = ""; proposals, and this is one of the main reasons why they're not recommendable.
There's no point in assigning a value to a variable if you're just going to overwrite it before you're going to use it. It hurts readability, and may potentially even hide bugs, e.g. when one execution path fails to overwrite this "initial" value.
References
Summary
- Don't "initialize" a local variable just for the sake of doing it if you're going to overwrite it anyway
- Let it be uninitialized, so that the compiler can help you identify a possible bug by pointing out any use of the variable while it's still uninitialized
- If the code compiles, then the variable is assigned a "real" value at least once before all uses
- If you don't need to reassign a local variable, make it
final to enhance readability
final immediately assures readers that no further reassignments are possible
- The compiler can help you prevent making the mistake of subsequent reassignment
- If the code compiles, then the variable is assigned a "real" value exactly once before all uses
- Generally speaking, you should let the compiler help you write the best, most readable code.
Dead store to myStringwarning in FindBugs, I'd hope