Skip to content
Advertisement

char array not modified after passing trough a method that should modify it in java

Hello i have a problem with the code i’ve written down below. From what i’ve understand so far what is passed to the method is the memory reference of charArray thus the variable charArray and tabCar should point at the same memory place. thus the modification done in my method reverseArray should be seen but somehow the 2 print statement display the same array… Could somebody explain to me why ?

public static void reverseArray(char[] tabCar){
    int lastPlace = tabCar.length - 1;
    for(int i = 0 ; i < tabCar.length ; i++){
        char tempChar = tabCar[i];
        tabCar[i] = tabCar[lastPlace - i];
        tabCar[lastPlace - i] = tempChar;
    }
}

public static void main(String[] args) {
    char[] charArray = {'a','b','c','d','e','f'};
    System.out.println("Before reverseArray : " + Arrays.toString(charArray));
    reverseArray(charArray);
    System.out.println("After reverseArray : " + Arrays.toString(charArray));
}

Advertisement

Answer

since you are running the loop till tabCar.length whats happening is its reverting the changes once the i value becomes more than tabCar.lenght/2 that is :

a b c d e f --->original
f b c d e a ---> i=0
f e c d b a ---> i=1
f e d c b a ---> i=2
f e c d b a ---> i=3 (reverting the changes)
f b c d e a ---> i=4
a b c d e f ---> i=5

so you should stop the loop when it reaches the half way (tabCar.length/2)

public static void reverseArray(char[] tabCar) {
    int lastPlace = tabCar.length - 1;
    for (int i = 0; i < tabCar.length / 2; i++) {
        char tempChar = tabCar[i];
        tabCar[i] = tabCar[lastPlace - i];
        tabCar[lastPlace - i] = tempChar;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement