Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final variable interpretation

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?

like image 320
StuPointerException Avatar asked Aug 01 '13 12:08

StuPointerException


People also ask

What do you mean by final variable?

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.

Why are final variables used?

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.

What is final final and final variable method?

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().


1 Answers

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:

  • It's easy to see the whole context of the method - and if it's not, that's a problem in itself.
  • As it doesn't represent the state of an object (or class) the benefits of immutability don't really apply.
like image 81
Jon Skeet Avatar answered Oct 05 '22 17:10

Jon Skeet