In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.
As doing this can confer security and efficiency benefits, many of the Java standard library classes are final, such as java.lang.System and java.lang.String.
[3] This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.
When using static linking, the compiler can safely assume that methods and variables computable at compile-time may be inlined.
It is considered good practice to represent final constants in all uppercase, using underscore to separate words.
[7] Example: Any attempt to reassign radius, xPos, yPos, or zPos will result in a compile error.
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: where pos is an object with three properties pos.x, pos.y and pos.z.
Like full immutability, the use of final variables has great advantages, especially in optimization.
Though it appears to violate the final principle, the following is a legal statement: Since the obj variable goes out of scope with each iteration of the loop, it is actually redeclared each iteration, allowing the same token (i.e. obj) to be used to represent multiple variables.
If the above construction is violated by having an object in the tree that is not immutable, the expectation does not hold that anything reachable via the final variable is constant.
This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class.
In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs.