02 July 2010

Java never ever uses pass by reference

Hi folks,

Java never ever never uses pass by reference!

Pass by reference requires that, whenever you change the value of the reference, the value of the original object got changed.
By "change the value of the reference" I mean, use the assignment operator to do that.

Example:

class X
{
int dataMember;

X(int n)
{
dataMember = n;
}
static void m1()
{
X x = new X(10);
System.out.println("Before: " + x.dataMember);
m2(x);
System.out.println("After: " + x.dataMember);
}

static void m2(X x)
{
x = new X(30);
System.out.println("IN: " + x.dataMember);
}

public static void main(String[] args)
{
m1();
}
}
Result:

Before: 10
IN: 30
After: 10



So, In language such as C, pass by reference uses deference Pointers:


#include <stdio.h>

void wrong_pass_by_reference(int*);
void correct_pass_by_refence(int*);

int main(void)
{
int n = 0;
int *ptr = &n;

printf("Before 1: %i\n", *ptr);
wrong_pass_by_reference(ptr);
printf("After 1: %i\n", *ptr);

printf("Before 2: %i\n", *ptr);
correct_pass_by_refence(ptr);
printf("After 2: %i\n", *ptr);

return 0;
}

void wrong_pass_by_reference(int* i)
{
int x = 10;
i = &x;
printf("IN 1: %i\n", *i);
}
void correct_pass_by_refence(int* i)
{
*i = 200;
printf("IN 2: %i\n", *i);
}
Before 1: 0
IN 1: 10
After 1: 0
Before 2: 0
IN 2: 200
After 2: 200

So, Java uses an approach similar to the one used by C, but in Java you cannot deference a reference to an object, So you cannot use call by reference!
Post a Comment