If Java is strictly pass-by-value for non primitive, isn’t it better to establish coding standards like make all formal parameters of methods and constructors final? – to avoid confusion?
If Java is strictly pass-by-value for non primitive, isn’t it better to establish coding
Share
Java is strictly pass-by-value for ALL arguments and ALL results, irrespective of type.
And if you don’t understand, or don’t believe me, read Java is Pass-by-Value, Dammit!
Yes you could, but it would be a bad idea to do it for the reasons that you have given.
Declaring a method or constructor’s formal parameters to be
finalmeans something different to the meaning that you are trying to place on it. Specifically, it means that the parameter can’t be assigned to in the body of the method / constructor.Doing this has the following consequences:
It will actually change the meaning of the code in a way that could cause compilation errors in some cases. (These are good compilation errors … because they force the programmer to stop doing something that generally makes his code less clear. But fixing takes effort and requires retesting, etc.)
Seasoned Java programmers are not going to read into this the meaning that you intend. (Not that they should need to be reminded …).
Novice Java programmers are likely to be more confused … especially if they pick up the incorrect notion that declaring something to be
finalalters the argument passing semantics!So this does not achieve your aim.
The real solution is to educate people that Java ALWAYS uses pass-by-value. (And that includes beating up people who persist in spreading false information and doubt about this … like your question does!)
(In nearly all cases, it is good practice to not update formal parameters, and declaring them
finalprevents you doing this by accident. So this is good practice. But the reason it is good practice is not what you stated … and if you did put this into a coding standard with the reasoning that you gave, you would deserve to be roundly criticised.)And if you don’t understand, or don’t believe me, read Java is Pass-by-Value, Dammit!