What would be the reason for doing the below:
public void processSomething(final String hello, final String two, final Car car){}
as opposed to:
public void processSomething(String hello, String two, Car car){}
The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all.
The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment.
You can pass final variables as the parameters to methods in Java. 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.
It means that within the method, you can't assign new values to the parameters.
A common reason for wanting to do this is to be able to use the parameters within anonymous inner classes which can only reference final
local variables, including parameters.
Another reason for doing this is if your coding style favours declaring all local variables as final if possible. (Personally I try to treat them as final, but avoid actually declaring them that way, as it adds cruft.)
It means you cannot change the references. String is immutable, but if Car is mutable you can change the fields in that Car, you can't change it to another Car.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With