What does the final modifier mean on local variables and when should I use it?

John Mitchell

The final modifier was introduced for local variables in Java v1.1. As with using final on fields, its use means that the local variable may not be modifed inside that method. This means that the compiler can catch any invalid modifications made in the method and it may be able to make better optimizations since it knows more about the intentions of the code.

Note that with final local variables you may defer initialization as long as the variable is definitely assigned before any use and that it assigned a value exactly once.

So, use the final modifier on local variables when you want to make it clear that the variable is only assigned once during the method and never changed thereafter.