Reputation: 565
I get the output for the program mentioned below. In addition Ii also encounter an exception as:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ReverseOrder.main(ReverseOrder.java:15)
Why does this happen?
public class ReverseOrder {
public static void main(String[] args)
{
int anArray[]={1,2,3,4,5,6};
int anotherArray[]=new int[6];
for(int i=5,j=0;i>=0;i--,j++)
{
anotherArray[j]=anArray[i];
}
//System.out.println(anotherArray.length);
//System.out.println(anotherArray[2]);
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
}
}
Upvotes: 3
Views: 152
Reputation: 35577
Why do you use this way to reverse your array in first place. Any way
for(int j=0;j<=anotherArray.length;j++) should change to
for(int j=0;j<anotherArray.length;j++)
Consider this too, It is easy.
int anArray[]={1,2,3,4,5,6};
int temp=0;
for (int i=0;i<anArray.length/2;i++){
temp=anArray[i];
anArray[i]=anArray[anArray.length-(1+i)];
anArray[anArray.length-(1+i)]=temp;
}
Now your array is reversed.
Upvotes: 0
Reputation: 51523
The problem is here:
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
you are accessing a position out of the array. This happen because method length
gives you the number of elements in the array, and since the first position of an array is 0 and not 1 you should end the loop on anotherArray.length - 1
and not anotherArray.length
.
There are two possible solutions to this where you modify your loop to:
a) for(int j=0;j<=anotherArray.length - 1;j++)
or
b)for(int j=0;j<anotherArray.length;j++)
The latter (b) is preferable, since it has less arithmetic operations on it.
Upvotes: 3
Reputation:
for(int j=0;j<anotherArray.length;j++)
instead of
for(int j=0;j<=anotherArray.length;j++)
Because arrays are zero-based in Java.
Upvotes: 2
Reputation: 18848
You will get ArrayIndexOutOfBoundsException when you try access the element that's out of Array limit.
for(int j=0;j<anotherArray.length;j++) {
System.out.println(anotherArray[j]);
}
Upvotes: 0
Reputation: 1600
Change
for(int j=0;j<=anotherArray.length;j++)
to
for(int j=0;j<anotherArray.length;j++)
Since if it's <=
you'll be going out of bounds.
In Java (and most languages), arrays are zero-based. If you have an array of size N
then its indexes will be from 0
to N - 1
(total size of N
).
Upvotes: 3
Reputation: 240948
change
<=anotherArray.length
to
< anotherArray.length
For example, if array is
int arr[] = new int[2];
arr.length; // it will be 2, which is [0] and [1] so you can't go upto <=length,
// that way you will access [2] which is invalid and so the exception
Upvotes: 2