What are Different Parameter passing techniques in Programming?

Different Parameter passing techniques In Programming

If you have any programming experience you might know that almost all the popular programming languages support two parameter passing techniques namely: call-by-value and call-by-reference.

In the call-by-value technique, the actual parameters in the method call are copied to the dummy parameters in the method definition. So, whatever changes are performed on the dummy parameters, they are not reflected on the actual parameters as the changes you make are done to the copies and to the originals.

In the call-by-reference technique, reference (address) of the actual parameters are passed to the dummy parameters in the method definition. So, whatever changes are performed on the dummy parameters, they are reflected on the actual parameters too as both references point to same memory locations containing the original values.

To make the concept more simple, let’s consider the following code segment which demonstrates pass-by-value. This is a program for exchanging values in two variables:

class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
class SwapDemo
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println(“Before swapping value of a is “+obj.a+” value of b is “+obj.b);
obj.swap(obj.a, obj.b);
System.out.println(“After swapping value of a is “+obj.a+” value of b is “+obj.b);
}
}

The output of the above programming will be:

Before swapping value of a is 10 value of b is 20
After swapping value of a is 10 value of b is 20

Although values of x and y are interchanged, those changes are not reflected on a and b. Memory representation of variables is shown in below figure:

Let’s consider the following code segment which demonstrates pass-by-reference. This is a program for exchanging values in two variables:

class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class SwapDemo
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println(“Before swapping value of a is “+obj.a+” value of b is “+obj.b);
obj.swap(obj);
System.out.println(“After swapping value of a is “+obj.a+” value of b is “+obj.b);
}
}

The output of the above programming will be:

Before swapping value of a is 10 value of b is 20
After swapping value of a is 20 value of b is 10

The changes performed inside the method swap are reflected on a and b as we have passed the reference obj into ref that is very much as using the same object within both brackets (from where it is called and to where it is) which also points to the same memory locations as obj.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.