Need help with for each loop section of java course


I am currently in your Ultimate Java course part 1, the For Each Loop section and run into the following problem.

As you can see the “For” and “For Each” loops run as expected. But the third loop gives the following exception. Hovering over the highlighted “x > 0”, informs me that this statement is always true.

Using the latest Java JDK and InteliJ editor.

Thank you in advance!

In Java the first element in an array is at index 0. So in an array with three elements, the last element is at index 2.

The error message says “Index 3 is out of bounds for length 3” because you initialize x with the length of the array which is 3 and not a valid index for the array. To iterate the array in reverse order you have to start at length - 1 and change the condition to x >= 0.

1 Like

That’s the piece that makes this concept click. Thank you!!

I cannot wait to try this tonight.

Thank you again!