++i
increments the value - it actually changes it (and evaluates as the updated value.)
++i
, i++
and the subtle distinction between them has been the cause of many and frustrating bugs. This is just my opinion, but I advise never using either one of them except as a single-line statement when you need to increment something. The brevity isn't worth the risk of bugs.
So if you enter printArray
with i=arr.length-1
, then you get past your i guard, increment i, make the recursive call (which returns), and then try to access `arr[arr.length - 1 + 1], which is out of bounds.
If you're just learning about recursion, you might be confused at how local variables and returns work in a method. Each time you call a method, that's a new stack frame (a section of memory) with completely different values for its local variables, and which returns independently. i
is not "i
in every usage of the method named printArray
", it's only "i
in the current application of the method printArray
." Similarly when you return, you cease to run the current application of printArray
, but not every application.
Sorry if that part's all stuff you know - I find it's one of those things that's completely mind boggling to people starting out, and then becomes completely obvious a week later.