Search code examples
javafinal

Final method arguments vs re-declaration of arguments as final variables in the method


I found a method similar to the following:

private void methodA(String firstArg, String secondArg) {
    final String queueFirstArg = firstArg;
    final String queueSecondArg = secondArg;
    executor.execute(new Runnable() {
        public void run() {
           methodB(queueFirstArg, queueSecondArg);
        }
    }
}

It looks like bad code and making both arguments 'final' would be enough. Am I missing something? Is there any benefit in using that approach?


Solution

  • Yes, it's "bad code" because of redundant local variables, because you can add final to arguments without afraid to change caller behavior, see answer:

    Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code.