We all are familier with two methods of paramter passing - call by value and call by refenence. Now the question arises java supports call by value or call by reference. Lets just for the time being consider few examples and then decide what java follows.
int n = 10;
doubleNumber(n);
Declaration of doubleNumber(...)
public void doubleNumber(int num){ //line 1
num = num * 2; //line 2
}
In the above example when line 1 is encountered,JVM makes a copy of the variable "n". When the control is returend from the function the variable num is no longer in the memory, so originally declared variable "n" remains unchanged in state. Hence by the above example we conclude that java supports call by value.
Now lets try our hands on some objects( Remember int was a primitive type not an object)
Employee emp = new Employee();
raiseSalary(emp);
public void raiseSalary(Employee e){//Line 1
e.setSalary(e.getSalary()*2);
}
Now when the call returns to the caller method surprisingly the value of the salary referred by original object "emp" changes. This happens because at line 1 variable e contains the copy of value at emp ie object refernce. Now both e and emp point to same memory location. So after return object e is collected by the garbage collector but the changes are reflected back . But does that means that java follows pass by reference. Well the answer is NO. Lets understand it with the same Employee class. Take a deep look at the emample below:
Employee emp1 = new Employee();
Employee emp2 = new Employee();
swapEmpObjects(emp1,emp2);
public void swapEmpObjects(Employee obj1,Employee obj2){
Employee temp;
temp = obj1;
obj1 = obj2;
obj2 = temp;
}
Now what happens is obj1 and obj2 contains object reference to emp1 and emp2. After the control returns from the function obj1 and obj2 gets interchanged that is their object reference changes. Since copy of object reference is contained in obj1 and obj2, the objects emp1 and emp2 remains unaltered. In nutshell object referene are passed by value in java. Hence java supports call by value.
No comments:
Post a Comment