In the “hidden features of java” question, someone mentions that final initialization can be postponed and provides an example:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 22";
} else {
element = "Result 3";
}
return element;
}
The poster says:
It’s too easy to miss a case and return null by accident. It doesn’t make returning null impossible, just obvious that it’s on purpose.
However I cannot wrap my head around what this means. How is this any different if element was not declared final? Wouldn’t the else statement always ensure that null is not returned? I’m thinking this is more a cosmetic thing rather than actually effecting the way the code operates.
The way you posted the question, the poster seems to be saying that if you did:
And then set it via the if methods, you could return null by accident (if you didn’t construct your else statement correctly), so take advantage of the fact that final initialization can be differed to after declaration.
However, the example is superfluous, because the compiler guarantees that this variable will be set before being used because it is local.
More interesting would be a case like this:
In that case the compiler will warn you if you never set element, rather than setting it to null for you, which is what would happen if it was not declared final.
In summary, what is interesting to know is that a final field or variable doesn’t have to be set where it is declared (as you might be inclined to think). Final means that it can only be set to a given value once, not that it has to be set on the same line as it is declared.