No matter how often we use final keyword in our Java program, but we should use the final keyword liberally to communicate our intent.
The final keyword has more than one meaning :
-
A final class cannot be extended.
-
A final method cannot be overridden.
-
A final field, parameter and local variable cannot change their
value once set.
In the last case, "value" for primitives is understood in the usual sense,
while "value" for objects means the object's identity, not its state. Once
the identity of a final object reference is set, it can still
change its state, but not its identity.
Declaring primitive fields as final automatically ensures thread-safety
for that field.
Some habitually declare parameters as final, since this almost
always the desired behaviour. Others find this verbose, and of little real benefit.
Consistently using final with local variables (when appropriate)
can be useful as well. It brings attention to the non-final local
variables, which usually have more logic associated with them (e.g:- result
variables, accumulators, loop variables). Many find this verbose.
A reasonable approach is to use final for local variables only if there is
at least one non-final local variable in the method ; this serves
to quickly distinguish the non-final local variables from the
others.
So here have the advantages of using final :
- Clearly communicates your intent
- Allows the compiler and virtual machine to perform minor optimizations
- Clearly flags items which are simpler in behavior - final says,
"If you are looking for complexity, you won't find it here."