Here we are going to discuss regarding how call by value and call by reference works in java and the way it take issue from c/c++ .If we glance at the conception of call by value then we are able to say that it uses variable’s values in argument section of method
Values are passed by argument section of function.Whereas in metter regarding call by reference,then we are able to say that it really take the reference of explicit class ,with the help of object we are able to pass the reference to the required class.In c/c++ we can simply pass the value or parameter with this two method.But when we talking regarding java then it’s completely different.
void cal(int i,int j)
class temp{
In java when you pass arguments to method by value,The parameters that receives argument has no effect outside the function.You will get better idea if you execute this two below listed programs.
Program of call by value in java
This method copies the vale of arguments into formal parameter.
Source code
class temp{
void cal(int i,int j)
{
i=i+2;
j=j-2;
}
}
class callvalue{
public static void main(String args[]){
int a=10,b=20;
temp obj=new temp();
System.out.println(“Before calculation”);
System.out.println(“a= “+a+” and”+” b= “+b);
obj.cal(a,b);
System.out.println(“After calculation”);
System.out.println(“a= “+a+” and”+” b= “+b);
}
}
Output
Before calculation
a=10 and b=20
After calculation
a=10 and b=20
Here we can see that when we actually try to pass the values to function of different class with it’s object .It perform the operation well but when it return to the main class the value of two variable will be same.
Program of call by reference
Source code
class temp{
int a,b;
temp(int i,int j)
{
a=i;
b=j;
}
void cal(temp t)
{
t.a=t.a+2;
t.b=t.b+2;
}
}
class callref{
public static void main(String args[])
{
temp obj=new temp(10,20);
System.out.println(“Before calculation”);
System.out.println(“a= “+obj.a+” and”+” b= “+obj.b);
obj.cal(obj);
System.out.println(“Before calculation”);
System.out.println(“a= “+obj.a+” and”+” b= “+obj.b);
}
}
Output image:-
Before calculation
a=10 and b=20
After calculation
a=20 and b=10
a=10 and b=20
After calculation
a=20 and b=10
Here we can see that the value which we got at the end of execution is differ from the actual value.So we can say that the concept of call by reference working well in java.We have used object as argument,and with that object we have changed that two values.If you have any query then contact us or comment below.