Java

What are different parameter passing techniques in Java Programming3 min read

This article explains about the parameter passing techniques in programming languages in general and how Java handles parameters in methods. Sample code is also provided which demonstrates the parameter passing techniques.

Parameter passing techniques 




If you have any previous programming experience you might know that most of the popular programming languages support two parameter passing techniques namely: pass-by-value and pass-by-reference.

In pass-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 pass-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:

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 are interchanged, those changes are not reflected on a and b.

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

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 which also points to the same memory locations as obj. Memory representation of variables is shown in below figure:

Take your time to comment on this article.

Leave a Comment