You are on page 1of 3

Program 05 :- Write a program in Java to perform Call by value and

Call by reference.

1 Introduction

Call by Value means calling a method with a parameter as value. Through this, the
argument value is passed to the parameter.

While Call by Reference means calling a method with a parameter as a reference.


Through this, the argument reference is passed to the parameter.

In call by value, the modification done to the parameter passed does not reflect in the
caller's scope while in the call by reference, the modification done to the parameter passed
are persistent and changes are reflected in the caller's scope.

1. Call By Value :-

The following program shows an example of passing a parameter by value. The values
of the arguments remain the same even after the method invocation.
//Java program to perform call by value
class Text {
int copy(int a, int b)
{
System.out.println("Value before Increment= "+a+" and "+b);
a++; b++;
System.out.println("Value after Increment= "+a+" and "+b);
return 0;
}
}
public class CallbyValue { public static
void main(String[] args) {
Text obj= new Text();
int A=5;
int B=6;
obj.copy(A,B);
}
}
/*Output

2. Call By Reference :-

Java uses only call by value while passing reference variables as well. It creates a copy
of references and passes them as valuable to the methods. As reference points to same
address of object, creating a copy of reference is of no harm. But if new object is assigned
to reference it will not be reflected.
//Java program to perform call by reference
class Text { int x,y;
Text(int a, int b)
{
x=a;
y=b;
}
void copy()
{
System.out.println("Value before Increment= "+x+" and "+y);
x++; y++;
System.out.println("Value after Increment= "+x+" and "+y);
}
}
public class CallbyRefrence {
public static void main(String[] args) {
int A=5;
int B=8;
Text obj= new Text(A,B);
obj.copy();
}
}
/*Output

Conclusion

Functions can be summoned in two ways: Call by Value and Call by Reference. Call by
Value method parameters values are copied to another variable and then the copied object
is passed, that’s why it’s called pass by value where actual value does not change.

In Java “Call by Reference” means passing a reference (i.e. memory address) of the object
by value to a method. We know that a variable of class type contains a reference (i.e.
address) to an object, not object itself.

You might also like