Thursday, December 12, 2013

Java: Pass By Reference or Pass By Value?

Many beginners of Java programming has the same question. When you put an object into an array, is it pass by value or pass by reference?

Well, let's see an example.


public class Test {

public static class A {
public String str;
}

public static void main(String[] args){
A[] array = new A[1];

A a = new A();
a.str = "Hey";
array[0] = a;
a.str = "Hello";
System.out.println(a.str);
System.out.println(array[0].str);

}
}

What do you think it will display? If Java is pass by value, then array[0] = a is actually copying the object and put it into the array, and as a result,  list.get(0).str should be "Hey".

However, the output is like this:
Hello

Hello

So, it is pass by reference? Actually, No.

Every object reference is storing the memory address of an object only. For example, 
A a = new A();
a is storing the address of the block of memory space containing the newly created object. When it is put in the list,
array[0] = a;
it is actually copying the address into the array.

It is easier to understand if we modify the above program to pass a primitive type value into the array:

public class Test {

public static void main(String[] args){
int a;
int[] array = new int[1];

a = 0;
array[0] = a;
a = 1;
System.out.println(a);
System.out.println(array[0]);

}

}

1

0

array[0] = a is actually copying 0 into array[0], so assigning new value to a will not affect the value of array[0].



No comments: