-1

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

Karam_404
  • 1
  • 5
  • You're starting at the length of the array, `int k = fruits.length` -- that's beyond what the array allows since arrays are 0-based and go from 0 to length - 1. More importantly, you will want to learn to use and practice using your debugger – Hovercraft Full Of Eels Mar 31 '20 at 22:54

1 Answers1

3

Array indexes for a Java array start at 0. So if there are 3 things in the array, their indexes are 0, 1 and 2.

You've set up your loop so that it starts at k = 3, and on subsequent iterations (if it reached them), it would have k = 2 then k = 1.

But these don't match the indexes in the array. In particular, when k = 3, there's no matching entry in the array, which is what's making your program crash.

You need to change the way your loop is set up, so that it iterates k = 2, then k = 1, then k = 0. May I suggest the following change?

for (int k = fruits.length - 1; k >= 0; k--) {

Everything else can stay the same.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110