Search code examples
javapass-by-referencebubble-sortpass-by-value

How can a void sorting algorithm "return" a result?


public static void main(String[] args) {
    int sizeOfTestArray = 50;
    int[] testArray = new int[sizeOfTestArray];
    Random random = new Random();
    for (int i = 0; i < sizeOfTestArray; i++) {
        testArray[i] = random.nextInt(100);
    }

    System.out.println(Arrays.toString(testArray));
    bubbleSort(testArray);
    System.out.println(Arrays.toString(testArray));
}

public static void bubbleSort(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

If Java is pass-by-value how is it that I can manipulate testArray inside my bubbleSort method and "return" the bubbleSorted testArray? Shouldn't the bubbleSorted testArray be destroyed after my program exits the bubbleSort method? Please help me understand this as I am getting conflicting information online as to whether or not Java is pass-by-value or pass-by-reference.


Solution

  • If Java is pass-by-value how is it that I can manipulate testArray inside my bubbleSort method and "return" the bubbleSorted testArray?

    Because arrays are mutable: Their state can be changed. So the method doesn't return anything, but it does change the state of the object referenced by the value you pass in.

    What you're passing in (an object reference) is passed by value. But the object it refers to is elsewhere in memory, the reference is just a means of telling the JVM where it is. This is a different usage of the word "reference" than the one in pass-by-reference (which specifically is about a reference to a variable, not an object).