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

Possible duplicate:
Is Java passing by reference?

I'm a little confused here. How does Arrays.sort (a) change the value?

int[] a = {9,8,7,6,5,4,3,2,1}; Arrays.sort(a); System.out.println(Arrays.toString(a)); 

I thought java passed by value ...

+6
source share
6 answers

Yes, Java is bandwidth. However, what is passed by value here is a reference to an array, not an array.

+10
source

Objects in Java are passed by reference value. Therefore, if you pass an object, it receives a copy of the link (if you assign this link to something else, only the parameter changes, the original object still exists and the main program refers to it).

This link demonstrates a bit of passing by the value of the link .

 public void badSwap(Integer var1, Integer var2) { Integer temp = var1; var1 = var2; var2 = temp; } 

These are object references, but they will not be replaced, as they are only internal references in the function area. However, if you do this:

var1.doubleValue();

It will use the link to the source object.

+6
source

Arrays.sort does not change the variable, it changes the array object that the variable points to.

+5
source

True, Java always passes by value and for objects an object reference , passing by value. Thus, the link of your array is passed by value.

+2
source
  • He sorts it.
  • An array reference is passed by value. Not the array itself.
+1
source

An array reference is passed by value, so the sort method has its own reference, which still refers to the same array as a . This means that sort can modify the contents of the same array as references a .

0
source

Source: https://habr.com/ru/post/916683/


All Articles