Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of "final" for method parameter in Java

I read with interest this question : Can I pass parameters by reference in Java?

What comes out it is that parameters (which are not primitives) are passed by copying the reference value. And so as the example states; you can't modify the reference of the parameter you gave:

Object o = "Hello";
mutate(o)
System.out.println(o); // Will print Hello

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

This kind of problem could be avoided using finallike this :

private void mutate(final Object o) { o = "Goodbye"; } //Compilation error

The questions :

  • Is the final keyword in such a case only used to throw a compilation error ?
  • If in the end you can't modify the reference of the given parameter why isn't final implicit or mandatory ?

I rarely used final for method parameters in Java but now I can't think of any case where you would voluntarily omit to put final to a method parameter.

Thanks!

like image 263
Michael Laffargue Avatar asked Apr 19 '26 14:04

Michael Laffargue


1 Answers

I usually do this to prevent accidental or unintended modifications of this reference. e.g.

private String doSomething(final String arg) {
   // final to prevent me doing something stupid!
}

One interesting scenario is in setters. You want to ensure that you set the member variable and not the arg passed in. e.g.

public void setArg(String arg) {
   _arg = arg;
}

In the above scenario, if the method parameter is not final, then I could possibly set

   arg = arg;

by mistake. The above is a common typo, or can occur due to search/replace refactoring. By making arg final, you can't accidentally reassign it.

like image 139
Brian Agnew Avatar answered Apr 21 '26 04:04

Brian Agnew