Tuesday 22 September 2020

Learn Recursion in Java

Recursive programming is surprisingly hard to learn for something that, in essence, is really quite simple. A recursive function is one that calls itself. So, you might have a function called x() which somewhere inside its code calls itself x() rather than some other function such as y()

Recursion is a very valuable technique when you want a function to do an operation a certain number of times until it’s run out of things to do. For example, if you want to count all the files in a set of subdirectories you can use recursion to keep looking for more subdirectories until there are no more subdirectories (or subdirectories of subdirectories) to recurse. Then you can count the files in each subdirectory. This sounds like it should be easy to do – and in essence it is. But unless you really understand how recursion works, it can be tricky. 

I teach a whole course on recursion and I also have a book. Either one will teach you all you need to know to understand recursion – what the stack is; how frames are added to and removed from the stack whenever a function is called; how to save values from recursive functions; how to return values; how to avoid infinite recursion and more…

My course normally costs $45 but if you click this link you can enroll for just $19 (plus any local taxes applicable): https://bitwisecourses.com/p/recursion-for-programmers/?product_id=778235&coupon_code=RECUR01

(Valid until end of October)

Alternatively, you can buy my book, The Little Book Of Recursion, from Amazon:

Amazon (US) https://amzn.to/2JjrJtq

Amazon (UK) https://amzn.to/2YCYx5N

Or search for its ISBN: 978-1913132057

The code examples in the course and book are mainly given in C and Ruby. However, recursion works in a similar way in all mainstream languages. To prove this, I’ve translated most of the C code into Java. You can get all the free source code (C, Ruby and Java) just by signing up to my mailing list and I’ll send you the download link: www.bitwisebooks.com

Meanwhile, here’s a short lesson explaining how to write just about the simplest possible recursive function in Java…