Therefore: Wrap the parameter in a container object:
class Wrapper { public int value; }However: This smells funny, so see AlternativesToPassByReferencevoid incrementValue (Wrapper wrapper) { wrapper.value++; }
...
Wrapper wrapper = new Wrapper(); wrapper.value = 2; incrementValue (wrapper); System.out.println (wrapper.value);
3
Also, this increases the number of classes. This will increase download time if the application or applet is loaded across the network. One or two classes may not matter, but if you need a lot of wrapper classes, either use arrays or try to refactor your code to avoid by-reference parameters.
See also: PassParameterInArray
Just returning a primitive value does not work when you have two or more parameters. The example above, which wraps a primitive type, is practically identical to an example where one would wrap an object reference.
To answer the "Java passes objects by reference automatically, right?" question: There are two things to remember:
# Java passes all parameters by value. # The passed value can be a reference to an object or a primitive type.
This page mirrored in JavaIdioms as of April 29, 2006