Monday, September 29, 2008

Java is ' Pass by Value'

Java is pass by value. Here is a simple example to explain the same. 

public class Animal{
public static void main(String a[]){
Dog d = new Dog();
d.type = "Golden Retreiver";
d.setDogType(d);
System.out.println(d.type);
d.setNewDogType(d);
System.out.println(d.type);
}
}

class Dog{
public String type="";
public void setDogType(Dog d) {
d.type="Pug";
}
//Try to change the reference of the existing object
//Surprisingly it does not change...
//It just means java is pass by value and not pass by reference
//The value of reference(memory location) of dog d is passed
//so when u do a new, this change happens in a temporary location
//there is no effect on the calling method object
public void setNewDogType(Dog d) {
d= new Dog();
d.type="Boxer";
}
}

Result: Pug Pug

What happens in the back ground is simple, the address of the memory location is copied to a temporary location which is then used by the called function. So when you modify the object using the passed object will make you feel you are dealing with a reference, but when you try to destroy the old reference and create a new one by using 'new', you just cannot.