2

I have this very little program in Java (just started to learn this language):

package hellojava;

public class Hellojava {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int[] nums = {1,2,3,4,5,6,7,8,9,10};
        int[] revs = reverse(nums);
        for (int i : revs) {
            System.out.println(revs[i]);
        }
    }

    public static int[] reverse(int[] list) {
        int[] result = new int[list.length];
        for (int i=0, j=result.length-1; i<list.length; i++, j--) {
            result[j] = list[i];
        }
        return result;
    }
}

It throws this error:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at hellojava.Hellojava.main(Hellojava.java:9).

So I pretty know what's wrong and know how to fix it, but my question is about that for loop. I thought that this enhanced for loop will work here, but it doesn't. Why's that?

4 Answers 4

10

The problem is that the enhanced for loop gives the values of the array, not the indexes. So, 10 the value is returned, which is an invalid index.

Your loop beginning:

for (int i : revs) {

is equivalent to

for (int index = 0; index < revs.length; index++)
{
    int i = revs[index];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Damn, it's so easy! Thank you! :)
5

The enhanced for loop gives you the values in an array, not the indexes. Try

for (int i : revs) {
    System.out.println(i);
}

Comments

3

Simple:

    for (int i : revs) {
        System.out.println(i);
    }

You are using a foreach statement instead of a for indexed loop. The foreach loop iterates the array for you and assign the element of the array to i so don't consider it as an index of an array.

Here is an Oracle documentation on the For-Each Loop.

Comments

3

Replace

System.out.println(revs[i]);

with

System.out.println(i);

Explanation: The variable i is the integer element and not an index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.