What is difference between call-by value and call-by sharing ?
I was reading this answer , it says JavaScript is call –by sharing ? If it is true then why Java is call-by value not call by sharing .
What is difference between call-by value and call-by sharing ?
I was reading this answer , it says JavaScript is call –by sharing ? If it is true then why Java is call-by value not call by sharing .
As Wikipedia states
the term "call by sharing" is not in common use; the terminology is inconsistent across different sources"
so while Java could be considered call by sharing it is not call this as the term doesn't have standard meaning.
Instead Java refers to "call by value" as the only variable types are primitives and references and these are always passed by value.
The key distinction you must have in mind is, what constitutes the value of an expression. In
int i = 2+3;
the value of i
is the number 5 itself. In
Date d = new Date();
the value of d
is a reference to a Date object, not the object itself.
Once you have that cleared, Java is a strictly pass-by-value language. This means that the value of an expression is copied to a new location private to the called method. It can modify that location with no effect on the calling method.
However, in
Date d = new Date();
modify(d);
the object referred to by d
is passed "by sharing": the called method gets a copy of the reference to the object, therefore it can modify the object in a way which the calling method will observe. What the called method cannot modify is the caller's reference to the object, so it cannot make the caller see another object when the method returns. Therefore
Date d = new Date();
Date d2 = d;
modify(d);
System.out.println(d2 == d);
is guaranteed to print true
whatever modify
does to its copy of the d
reference, or to the object it refers to. (Remember that ==
only compares values).