Using the final keyword means that the variable you declare is immutable. After the initial assignment, it cannot be reassigned.
However, this does not necessarily mean that the state of the instance referenced by the variable is unchanged, only the link itself.
There are several reasons why you would use the final keyword for variables. One of them is optimization, where, declaring a variable as final, the value is memoized .
Another scenario in which you must use the final variable is when the inner class inside the method needs to access the variable in the declaration method. The following code illustrates this:
public void foo() { final int x = 1; new Runnable() { @Override public void run() { int i = x; } }; }
If x is not declared as "final", the code will result in a compilation error. The exact reason for the need for a โfinalโ is that the new instance of the class can survive the method call and therefore needs its own instance of x. To avoid having multiple copies of a variable to be modified within the same scope, the variable must be declared final so that it cannot be changed.
Some programmers also advocate the use of "final" to prevent accidental redistribution of variables where they should not be. A rule type of best practice.
S73417H
source share