Call by Value

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

In case of call by value original value is not changed. Let's take a simple example:
 class CallByValue {
int data = 50;

void change (int data)
{
data += 100; ////changes will be in the local variable only
}

public static void main(String[] args) {
CallByValue cbv = new CallByValue();

System.out.println("Before Change : "+cbv.data);

cbv.change(500);
System.out.println("After Change : "+cbv.data);
}
}


Another Example of call by value in Java

In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:

public class CallByReference {
int data = 50;

void change ( CallByReference cbr)
{
data += 100; //changes will be in the instance variable
}

public static void main(String[] args) {
CallByReference cbr = new CallByReference();

System.out.println("before change "+cbr.data);
cbr.change(cbr);//passing object
System.out.println("after change "+cbr.data);
}
}











Comments