0

So I get that Java is a pass-by-copy language (at least as much as I've learned from the books so far). However, why does a code like that:

public static void main(String[] args) {
    (...)
System.out.println("Array before sorting: "+Arrays.toString(ourArray));
System.out.println("Array after sorting: "+Arrays.toString(sortTheArray(ourArray)));
System.out.println("Bah-dum-tss: "+Arrays.toString(ourArray));

}

public static int[] sortTheArray(int[] someArray)
{
    Arrays.sort(someArray);
    return someArray;
}

Produce the same output for the second and third line? I mean - if we pass it by copy only, why doesn't it just print the sorted array on the second println and then print the same, non-sorted one on the third? I don't do any ourArray = sortTheArray(ourArray) anywhere so why does the value of it change? Thank you in advance and sorry for a newbish question :)

Straightfw
  • 2,143
  • 5
  • 26
  • 39

5 Answers5

4

Java does not pass a copy of the entire array, it passes the value of the array's reference. So there is only one instance of the array in your application and that instance get's sorted.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
2

The short answer is: because your book is wrong. Java is pass by value. In this case the "value" is a reference to the int Array. This reference is passed into Arrays.sort() which will sort the array at that reference (which in your case is always the same. So you have on place where your array is, and all your code uses the very same one.

If you want to have a real copy you need to use System.arraycopy() to produce a new array which you then can modify without changing your original one.

Fabian Lange
  • 1,786
  • 1
  • 14
  • 18
1

The parameter ourArray is copied, so there are multiple references to the same array. The array is modified using one copy of the reference, and the change is visible via the other reference. ourArray doesn't change and continues to point to the same array as it did before.

fgb
  • 18,439
  • 2
  • 38
  • 52
1

You pass a copy of the reference, which points to the object.

This means that

 public void myMethod(Set<String> a)

then

 myClass.myMethod(b);

both b and myMethod's a will have the same value, the reference to the same object.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
0

This is most likely happening because the method sortTheArray is modifying the object that it operates on. If you're familiar with ruby you may have noticed that some methods have a trailing exclamation point. This means the method will modify the object it's called on.

Dillon Benson
  • 4,280
  • 4
  • 23
  • 25