In fact, @Dmitry V. already wrote about this - I don’t want to take someone else’s fame and made the answer general. I would like to expand a little.
In Java, there is no such action as passing an argument by reference; it was decided to abandon it in favor of transparency of actions and avoidance of non-obvious errors. So there is a simple rule:
In Java, all arguments are passed by value.
What to do in a situation similar to the situation in the question when you need to influence global variables from a method.
Immediately, we note that, although wrapping in containers and generics, although they solve the problem, it is unnecessarily difficult and not obvious when third-party code reads, it’s definitely not necessary to abandon it in such a solution.
Meanwhile, there is a simple "canonical" method of this action - the return value by the method:
class Main { int a = 0; public static void main(String args[]) { a = myMethod(a); } int myMethod(int b) { return b++; } }
In addition, if you are a Hindu at heart, then you can generally put on canons and conventions and work in the method directly from the global variable:
class Main { int a = 0; public static void main(String args[]) { myMethod(); } void myMethod() { a++; } }
In addition to the populated "common cultural" values of the language, we also see obvious shortcomings - the method is not universal and works with only one global variable, but this is to be a Hindu.
However, it is worth noting that this sarcasm will not be appropriate when using a global variable for its intended purpose - accessibility in all methods of the class. With this use, the value of a global variable can be changed directly in the methods, especially if changing it is not the purpose of the method and the method must return a different value (the code in this question does not apply to this type of use, therefore the first option is preferable).