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 :
final keyword in such a case only used to throw a compilation error ? 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!
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.
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