Tuesday, April 5, 2016

Java and pass by value

In programming language method arguments are passed by two ways :

1. Pass By value : A copy of the argument is stored in the memory location allocated for formal parameters.In this case any changes made inside method will not affect the value of the argument in the calling method.

2. pass by reference : the memory address of the argument is passed to the method, making the formal parameter an alias for the argument. This means that changes made to the formal parameter inside the method will be reflected in the value of the argument when control is returned to the calling function.


We are clear about java's pass by value behavior for primitive types. But most of us say that java uses pass by reference for object arguments and here we go wrong.
In case of object as an argument, a copy of the object reference is passed to the method(hence this copy of reference point to the same object).

Points to note :
1. Any changes made on the object reference in a method will affect the original object, since it points to the object.
2. Inside a method , if the reference is assigned to a new object, there will not be any change in the original object.

class Cat{
private String name;

public Cat(String name) {
this.name=name;
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

class Test {


 public void doStuff(Cat cat){
    cat=new Cat("cat2");

     }

     public void doStuff1(Cat cat){
    cat.setName("new name");

     }

public static void main(String[] args) {

     Cat cat=new Cat("cat1");
     TestMain test=new TestMain();
     test.doStuff(cat);
     System.out.println(cat.getName()); //will print cat1

     test.doStuff1(cat);
     System.out.println(cat.getName()); //will print new name



}

}

No comments:

Post a Comment