Thursday, June 11, 2009

Is Java "Pass By Reference" or "Pass by Value"?

Java is always "Pass By Value".

Live with the statement that
In Java, Object references are passed by values and primitives are passed by values.

Consider the following examples:
1. Primitives:
public static void main(String args[]){
int a = 5;
int b =10;
System.out.println("Before swap, a = " + a + " , b = " + b);
swap(a, b)
System.out.println("Afterswap, a = " + a + " , b = " + b);
}

public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}


Result:
You will see zero effect of the swap method, because the parameters are passed by values and the during swapping inside the swap method only the copies were modified.
2. Object References:
Class Person{
private String address;
public String getAddress(){
return this.address;
}
public void setAddress(String address){
this.address = address;
}
}

public static void main(String args[]){
Person a = new Person();
Person b = new Person();
a.setAddress("Address A");
b.setAddress("Address B");
swap(a, b);
}


public void swap(Person a, Person b){
Person temp = a;
a = b;
b = temp;
}


You will again see Person objects unaffected by the swap operation.

Now, if the swap function is modified as shown below

public void swap(Person a, Person b){
String tempAddress = a.getAddress();
a.setAddress(b.getAddress());
b.setAddress(tempAddress);
}


In this case, the original objects will be modified.

No comments:

Post a Comment