Possible Duplicate:
Is Java pass-by-reference?
I am a little confused here. How does Arrays.sort(a) modify the value of a?
int[] a = {9,8,7,6,5,4,3,2,1};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
I thought java was pass by value...
Yes, Java is pass-by-value. However, what is getting passed by value here is the reference to the array, not the array itself.
Objects in Java are passed by value of reference. So if you pass in an object, it gets a copy of the reference (if you assign that reference to something else, only the parameter is modified, the original object still exists and is referenced by the main program).
This link demonstrates a bit about passing by value of reference.
public void badSwap(Integer var1, Integer var2)
{
Integer temp = var1;
var1 = var2;
var2 = temp;
}
Those are references to objects, but they will not be swapped since they are only the internal references in the function scope. However, if you do this:
var1.doubleValue();
It will use the reference to the original object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With