Yakov Stoykov
Yakov Stoykov

Reputation: 65

Error in the code when working with arrays

Hy! Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException? package studing;

public class Array {

    public static void main(String[] args) {
        int i;
        int[] ar1 = new int[50];
        for(i = 0; i < ar1.length; i++)
        {
            ar1[i] = i * 2 + 1;
            System.out.print(ar1[i] + " ");
        };

        System.out.println();

        for(i = ar1.length; i > -1; i--)
        {
            ar1[i] = i * 2 - 1;
            System.out.print(ar1[i]);
        };

    }

}

After compiling the console displays:

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50 at studing.Array.main(Array.java:18)

I want the output console in the second row 99 97 95 93 ...

Thanks in advance!

Upvotes: 1

Views: 71

Answers (2)

Kristian H
Kristian H

Reputation: 174

The first time the second for loop runs, i = 50 (the initial value), which is beyond the end of the array. This value is used before the index update of i--, so ar1[50] is out of bounds (proper indexes are 0 to 49 for a 50 element array).

Upvotes: 1

Joffrey
Joffrey

Reputation: 37829

You start at ar1.length in your second loop, which is out of bounds.

To get it to work, you need to start at ar1.length-1, which is the maximum index for your array. This is because arrays are 0-based in Java, as noted in the comments by @Maroun Maroun.

Upvotes: 3

Related Questions