Marcos Aleman
Marcos Aleman

Reputation: 23

How do I reverse an array in Java?

I've tried this code but I am unsure as to why it does not work:

    String[] arr = {"A", "B", "C", "D", "E"};//AD
    String[] arr2 = arr;
    int last = arr.length-1;
    int first = 0;
    int size = arr.length;
    while (first < size) {
        arr2[first] = arr[last];
        last--;
        first++;
    }
    System.out.print(Arrays.toString(arr2));

Can anybody help?

Upvotes: 2

Views: 74

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15180

This line does not do what you think it does: String[] arr2 = arr. This is simply pointing the variable arr2 at the same object reference as arr. So changes in one will show up in the other, since they're effectively the same thing.

In order to reverse an array, you need to iterate through the array and copy the values to your reversed array.

String[] arr = { "A", "B", "C", "D", "E" };
String[] reversed = new String[arr.length];

for(int i = 0, j = arr.length-1 ; i < arr.length; i++, j--) {
  reversed[j] = arr[i];
}

Upvotes: 2

Related Questions