Categories
Mastering Development

what’s wrong with this for loop? weird error [duplicate]

I was learning about for loops and whenever I do this loop

String[] fruits = {"Apple", "Banana", "Orange"};
        for (int k = fruits.length;k > 0; k--) {
            System.out.println(fruits[k]);
}

and I get this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at helloworld.HelloWorld.main(HelloWorld.java:439)
Java Result: 1
BUILD SUCCESSFUL (total time: 10 seconds)

and I don’t want to do a for each loop.
Thanks in advance

Leave a Reply

Your email address will not be published. Required fields are marked *