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 final
like 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!