Tallan Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Java could be a pain to C# developers (Pass by Reference)

In 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.

String a = "a";
System.out.println(a); // 'a' gets printed
String[]  array = new String[]{a}; //add a copy of the pointer variable a to String  array

void modify(String[] array) 
     array[0] = "b";

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)

Share this post:

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>