Marcos Aleman Marcos Aleman - 3 years ago 196
Java Question

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?

Answer Source

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];
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download