Reputation: 3
I am currently trying to take the elements of an array and reverse its order in Java. How come I cannot print the elements of the array by counting downwards using a for loop without changing the actual ordering of elements in my array?
private void printArray(int[] array) {
for (int i = array.length; i >= 0; i--){
println(array[i]);
}
}
Upvotes: 0
Views: 133
Reputation: 121810
Array indices start at 0
and end at array.length - 1
. Here, you get an ArrayIndexOutOfBOundsException
since your first read is past the end of the array (int i = array.length;
).
Do:
for (int i = array.length - 1; i >= 0; i--)
println(array[i]);
Upvotes: 7
Reputation: 60017
Try
for (int i = array.length - 1; -1 != i; --i){
As indexes start from 0
Upvotes: 1