You must return it. The second example you provided is the path.
First of all, it is more clear. When other people read your code, there is no information that they may not notice that the parameter is changing as output. You can try to name the variables, but when it comes to code readability, this is preferable.
The reason BIG is why you should return it, and not pass it, with immutable objects. Your example, List, is modified, so it works fine. But if you try to use String in this way, it will not work.
Since strings are immutable if you pass the string as a parameter, then the function should say:
public void fun(String result){ result = "new string"; }
The value of the result you passed in will not be changed. Instead, the local variable "result" now points to a new line inside fun, but the result of your calling method still points to the original line.
If you called:
String test = "test"; fun(test); System.out.println(test);
It will print: "test", not "new line"!
So definitely, he surpasses the comeback. :)
source share