Pass by reference
March 6th, 2009In C++ and C#, developers have freedom to modify variables by directly having access to memory location.
In C++,
#include <stdio.h>
void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(a, b);
printf(”A is %d and B is %d\n”, a, b);
return 0;
}
In C#,
int a = 1;
modify(ref a); //now a=2
void modify(ref int a)
{
a = 2;
}
In Java, however, there’s no such thing as pass by reference. Even the so-called pointers (created by ‘new’ operator) are passed by copy of the reference.
Thus, if you do the following,
String a = “a”;
modify(a); //a doesn’t change, since a is being passed as a copy of the pointer a.
void modify(String a)
{
a = “b” //this a is a different pointer, thus does not affect the real ‘a’ pointer outside of the method.
}
As you can see, there’s no direct way of modifying the variable. This has become a problem for me in many cases, since from time to time, it is necessary to have direct access to the variables.
The answer is by using a wrapper.
Here’s an example.
public class Test {
public static void main(String[] args) {
String a = “a”;
System.out.println(a); // ‘a’ gets printed
String[] array = new String[]{a}; //adds a copy of pointer ‘a’ to String array
modify(array);
System.out.println(array[0]);
}
public static void modify(String[] array) {
array[0] = “b”; //instantiating a new object ‘b’ to the copy of variable a
}
}
This is not the most elegant way of doing it, but you get the idea.
One thing to remember is that String[] array contains a copy of pointer ‘a’. When you assign, or add, items to any collections such as array, you’re passing a copy of a pointer. So the variable ‘a’ in the example above still is pointing to the value ‘a’, whereas array[0] points to ‘b’. In order to finalize the pointer modification, you need to assign
a = array[0].
So, the basic idea is this: In Java, when you pass variables around, whether they are pointers or primitive values, you’re always dealing with a copy of the variables, not the variables themselves. If you understand the basic idea of it, you can take advantage of the true “Pass by Reference”.
I hope this sort of ‘trick/hack’ can be of help to you all.
-Seung Kim (SK)
