Have read a lot of stack overflow answers on this topic and also I have read many blogs. I can surely conclude that Java is pass by value.
But to convince people I need a proof of some language which is pass by ref.
So can someone give a live example of a language which is pass by reference by whose example we could relate that java is not pass by reference.
I don't know any languages which are pass-by-reference all the time, but C# has the ref
modifier which allows a specific parameter to use pass-by-reference. That allows you to see the difference pretty easily. For example:
using System;
public class Program
{
static void Main()
{
string x = "original x";
string y = "original y";
Modify(x, ref y);
Console.WriteLine(x);
Console.WriteLine(y);
}
static void Modify(string px, ref string py)
{
px = "modified x";
py = "modified y";
}
}
The output is
original x
modified y
That's because the assignment to px
doesn't affect x
in the calling code: the value of x
was passed to the method. But the assignment to py
does change y
, because y
was passed by reference; py
and y
are aliases for the same storage location, basically.
All of this only matters when you modify the parameters themselves. Compare the above program with this one:
using System;
using System.Text;
public class Program
{
static void Main()
{
StringBuilder x = new StringBuilder("original x");
Modify(x);
Console.WriteLine(x);
}
static void Modify(StringBuilder px)
{
px.Length = 0;
px.Append("modified x");
}
}
Now the Modify
method doesn't change the value of px
at all - instead of makes changes to the object that the value of px
refers to. No pass-by-reference is required - the value of x
is passed to the method by value, and that is copied into px
. This is like copying your home address on a piece of paper and giving it to someone. It's not copying the house itself - it's just copying the way of reaching the house. If the person you've given the paper to goes and paints the front door red, then when you go home you'll see that change.
This is why it's important to understand the difference between variables, objects and references.
See more on this question at Stackoverflow