Tutorial :Final initialization in java can be postponed, how does this prevent against returning null inadvertently?



Question:

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.


Solution:1

The way you posted the question, the poster seems to be saying that if you did:

 Object element = null;  

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:

public class SomeClass {       private final Object element;         public SomeClass(int index) {              if (index == 0) {                  element = "Result 1";              } else if (index == 1) {                  element = "Result 22";              } else {                  element = "Result 3";              }       }  }  

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.


Solution:2

Finals can only be set and never re-set. They are sometimes conflated with the concept of constants in java. More correctly they are immutable object references.

The catch is that if something is immutable, how and when do you set its initial value. The answer is that java checks that only one possible flow can assign a value to a final variable. That way you don't have to assign the value at declaration time.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »