I know how the compiler interprets the final keyword in Java, but how should us programmers interpret its meaning? Should it be:
1) This variable cannot be changed (used by inner class for example)
or
2) I'm not planning to change this variable (might have some optimisation benefits for member variables).
I'm asking because I've worked on code where everything is declared final by default (option 2 above) which, in my opinion, devalues the keyword and hides the values that really can't change! Is there still performance benefits in declaring variables final?
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed. So, the state of the object can be changed but not the reference.
Final variables can be used to construct trees of immutable objects. Once constructed, these objects are guaranteed not to change anymore. To achieve this, an immutable class must only have final fields, and these final fields may only have immutable types themselves.
12. Final methods are bonded during compile time also called static binding. 13. Final variables which are not initialized during declaration are called a blank final variable and must be initialized in all constructors either explicitly or by calling this().
Everything being final by default is a good thing. The more you can model your code on immutability, the easier it tends to be to reason about.
Using final
is hardly ever about performance in my opinion. It's about making assertions about the rest of the code (nothing changes this variable) which can help a reader to understand the code, and can be checked by the compiler.
EDIT: The above is my view for fields. For local variables (including parameters) I personally only use final
when the variable will be used in an anonymous inner class. This is different from fields because:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With