Pass by Value in Java

Price: INR 8,999.00
Price: INR 15,999.00
Was: INR 16,999.00

Java supports pass by value. Java doesn’t support pass by reference in Java. In this tutorial, we will explain the difference between pass by value and pass by reference.

Most importantly we need to be clear on what we mean by using the terminology “pass by value” and “pass by reference”.

Some people are saying that in Java primitives are passed by value and objects are passed by reference. It is not correct.

 

Pass by Value – In Pass by Value, The actual parameter is copied to another variable and then the copied object is passed. This mechanism is called pass by value and Java uses it.

Pass by reference – In pass by reference, An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

 

Pass by Value vs Pass by Reference

We execute a simple swap program and verify the pass by value vs pass by reference.

Let us pass two arguments and swap them inside the invoked method, then check if the actual arguments are swapped. If the actual arguments are affected then the mechanism used is pass by reference otherwise, it is pass by value.

Output :

Before Swap:- a1:BMW X1; a2:Audi A3
After Swap:- a1:BMW X1; a2:Audi A3

 

You can see in the above code, in the swap() method , we are trying to  swap the objects but in the result, we are not able to swap the objects.

 

Selenium Testing Video Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply