Java simple recursive function explanation [closed]

Here is the order that the recursion is going through. Each level of indentation indicates a deeper call.

myMethod(4)
 . counter is 4
 . print "hello4"
 . counter-- and is now 3
 . myMethod(3)
 . . counter is 3
 . . print "hello3"
 . . counter-- and is now 2
 . . myMethod(2)
 . . . counter is 2
 . . . print "hello2"
 . . . counter -- and is now 1
 . . . myMethod(1)
 . . . . counter is 1
 . . . . print "hello1"
 . . . . counter-- and is now 0
 . . . . myMethod(0)
 . . . . . counter is 0
 . . . . . return
 . . . . print counter "0"
 . . . . return
 . . . print counter "1"
 . . . return
 . . print counter "2"
 . . return
 . print counter "3"
 . return

To answer the OP’s question, the 0 / 1 / 2 / 3 print at the end because of the line of code:

System.out.println(""+counter);

Note that this gets called at each level of recursion, which is indicated by the counter.

Leave a Comment