I wrote code to reverse an integer array. Code is as shown below:
public class ReverseArray {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
for (int i = 0; i <= arr.length/2; i++)
int temp = arr[0];
arr[0] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
System.out.println(arr);
} catch (Exception e) {
System.out.println(e);
}
}
}
But it’s not reversing the array.. I’m getting following output.
[I@3bad086a
I don’t see anything wrong with my logic.
That is printing out the reference to the array.
If you print out the array one element at a time, you will see the reversed array.
EDIT:
Two more points.
arr[0]when you intend to usearr[i].arr.length / 2. Since this is a homework question, I leave it to you to find out why; try printing out the intermediate results and explaining them.