Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get ArrayIndexOutofBoundsException - reverse the array

Tags:

java

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]);
        }
    }
}
like image 578
RDPD Avatar asked Jul 18 '26 10:07

RDPD


1 Answers

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).

like image 109
Mark M Avatar answered Jul 20 '26 22:07

Mark M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!