Call by Value and call by Reference.


What is Call by Value and Call by Reference in Java

Call by value and call by reference or pass by value and pass by reference are two mechanisms to pass parameters to methods in a programming language.

Call By Value in Java :-

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 pass by value mechanism method is passed the value provided by the caller, therefore, changes made to the formal parameters of the method have no effect on the original values that were passed by the caller.

Example of call by value in java

In case of call by value original value is not changed. Let’s take a Example.

class Callvalue

{

int data=50;

void display(int data)

{

data=data+100;                                     //changes will be in the local variable only

}

public static void main(String args[])

{

Callvalue op=new Callvalue();

System.out.println(“before change “+op.data);

op.display(500);

System.out.println(“after change “+op.data);

}

}

output:

calljava

 

 

 

 

 

When you pass a simple type to a method, it is passed by value. The parameter that receives the argument has no effect outside the method. Here the operation occur inside display() method have no effect on the values of “data” used in the call. Their value didn’t change.

Call By Reference in Java :-

If we call a method passing a reference of object, it is known as Call by reference.It is also known as pass by reference. In 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:

Example of call by reference in java

class callbyref

{

int data=50;

 void display(callbyref op)

{

op.data=op.data+100; //changes will be in the instance variable  

 }

 public static void main(String args[])

{

   callbyref op=new callbyref();

   System.out.println(“before change “+op.data);

   op.display(op);   //passing object  

   System.out.println(“after change “+op.data);

 }

}

Output:

callref

 

 

 

 

 

 

 

 

When we pass an object to a method the situation change dramatically. Because objects are passed by Reference. When we creating a variable of a class type, you are only creating a reference to an object. Change to the object inside the method do effect the object used as an argument. When object reference is passed to a method, the reference itself is passed by use of call-by-value.

Comments are closed.