-1

I want to change first and last element in array, but it does not work. I try to debug my code, array change only in method reverseArray, but not in the main method. So can you explain how it work in Java.

import java.util.Arrays; public class Solution {

public static void main(String[] args) {
    int[] array = {11, 22, 33, 44, 55, 66, 77, 88, 99};
    printArray(array);
    reverseArray(array);
    printArray(array);
    System.out.println(Arrays.toString(array));
}

public static void reverseArray(int[] array) {
    int[] testArray = new int[array.length];
    for (int i = testArray.length-1;i>0;i--)
        testArray[i] = array[Math.abs(i - array.length+1)]; // Swap first and last element of array
    System.out.println(Arrays.toString(testArray)); //Check  testArray changed
    array = testArray;                             // 1 way 
    System.out.println(Arrays.toString(array));     // Check that array change by 1 way
    array =  Arrays.copyOf(testArray, array.length); // 2 way
    System.out.println(Arrays.toString(array)); // 
}

public static void printArray(int[] array) {
    for (int i : array) {
        System.out.print(i + ", ");
    }
    System.out.println();
}

}

Grey may
  • 3
  • 4
  • if you modified `array` directly then the object would be changed, but you are trying to assign a new Object. See [is-java-pass-by-reference-or-pass-by-value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Scary Wombat Sep 16 '22 at 04:25

1 Answers1

-2

Try doing this in the reverseArray() method. It will update the array.

for(int i=0; i<array.length; i++){
  arr[i] = testarray[i];
}

What you did i.e. Simply changing the array reference, would not make the caller see the difference coz the caller still keep the old reference.

fauzimh
  • 594
  • 4
  • 16