Let’s try to understand how pass by value and pass by reference works in Java.
It is very simple and read the next sentence twice☺️. In Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (or copy-by-value) works.
Look at the example given below:
Here methodOne invokes methodTwo and passes an int type a whose value is 10. methodTwo is accepting this in a variable called c and incrementing its value by one inside the method. Also it returns the incremented value. A copy of the value is passed from methodOne to methodTwo and there is no change in the actual value of a in methodOne.
So what happens if an object reference is passed instead of primitive type int ?
Here methodOne invokes methodTwo and passes an object reference of Car type which is c which has an attribute called color whose values is black. methodTwo is accepting this in a variable called d and changing it’s color attribute to white. A copy of the object reference is passed from methodOne to methodTwo and a change in the attribute value in methodTwo will get reflected in methodOne too. Because it is actually modifying the original object through copied reference.
In pass-by-value the caller(methodOne) and callee(methodTwo) have two independent variables with the same value. A change in callee’s parameter variable, will not get reflected in caller’s variable.
In pass-by-reference the caller(methodOne) and the callee(methodTwo) use the same variable for the parameter. A change in callee’s parameter variable, reflects in caller’s variable too.
About the author: Amrutha is working as a Junior Consultant in jThread IT Training & Consultancy.