Pass an integer by referenceTag(s): String/Number

Sometimes you may need to pass an integer to be able to change its value. "integer" are always passed by value in Java. An easy way to pass by reference is to use a single element array.
int[] a = new int[1];
a[0] = 1;
add2(a);
// a[0] now = 3
...

void add2(int[] a) {
    a[0] = a[0] + 2;
}



If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]