call by value in Java:
If a method is to be called by passing a parameter as a value then it is said to be Call by Value. Here the changes made to the passed parameter do not affect the called method.
Example of call by value:
class CallByValue
{
void meth(int x, int y)
{
x = x + 10;
y = y - 20;
System.out.println("The result after the operation performed:");
System.out.println("a = " + x + "\t b = " + y);
}
}
public class JavaMain
{
public static void main(String args[])
{
CallByValue obj = new CallByValue();
int a =50, b = 100;
System.out.println("The value of a and b before the call :");
System.out.println("a = " + a + "\t b = " + b);
obj.meth(a, b);
System.out.println("The value of a and b after the call : ");
System.out.println("a = " + a + "\t b = " + b);
}
}
Output:
a = 50 b = 100
The result after the operation performed:
a = 60 b = 80
The value of a and b after the call :
a = 50 b = 100
call by reference in Java:
If a method is to be called by passing a parameter (not the value) as a reference then it is said to be Call by Reference. Here the changes are made to the passed parameter effect on the called method.
Example of call by reference:
class CallByRef
{
int x, y;
CallByRef(int i, int j)
{
x = i;
y = j;
}
/* pass an object */
void method(CallByRef p)
{
p.x = p.x + 2;
p.y = p.y + 2;
}
}
public class JavaMain
{
public static void main(String args[])
{
CallByRef obj = new CallByRef(10, 20);
int x = 10, y = 20;
System.out.println("The value of a and b before the call :");
System.out.println("a = " + obj.x + "\t b = " + obj.y);
obj.method(obj);
System.out.println("The value of a and b after the call : ");
System.out.println("a = " + obj.x + "\t b = " + obj.y);
}
}
Output:
The value of a and b before the call :
a = 10 b = 20
The value of a and b after the call :
a = 12 b = 22