Lesson 21 of 34
Recursion: Methods That Call Themselves
10 min 35 XP
A recursive method calls itself with a smaller input. It needs a base case (where it stops) and a recursive case (a call on a smaller problem). Without a base case you get a StackOverflowError.
Example: edit me and press Run
Output Loading Java (first time takes a few seconds)
Press Run to see the result here.sumTo(3) = 3 + sumTo(2) = 3 + 2 + sumTo(1) = 3 + 2 + 1 + sumTo(0) = 6. Tracing it on paper like this makes recursion click.