Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Arrays.sort() change the variable passed to it? [duplicate]

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...

like image 809
Josh Avatar asked May 25 '12 15:05

Josh


2 Answers

Yes, Java is pass-by-value. However, what is getting passed by value here is the reference to the array, not the array itself.

like image 160
NPE Avatar answered Nov 15 '22 18:11

NPE


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.

like image 45
David B Avatar answered Nov 15 '22 18:11

David B