Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java recursion using Eclipse's debugger

I am going through some simple recursion exercises in Java in order to understand the concept (which I struggle with). For all my study up to this point, I have relied heavily on Eclipse's debugger in order to understand exactly what my code is doing. However, when it comes to recursion, I find this not to be the case, because it is difficult to track exactly what is happening.

Considering the following code, a method that returns the nth Fibonacci number:

public int fibonacci(int n) {
    if (n == 0 || n == 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

When using the debugger for this code, it's pretty difficult to track exactly what is happening and where/when. With only one variable, it changes every step, and, with a small n value, such as 7, it is already becoming difficult to track, due to the fact that there are so many steps that are executed before 13 is eventually reached.

I would like to know:

  1. How can I debug my recursion code (in general) in a better way, in order to better understand recursion?
  2. Am I focussing too much on debugging for this sort of thing, considering the concept return fibonacci(n - 1) + fibonacci(n - 2) is simple to understand?
like image 775
alanbuchanan Avatar asked Apr 22 '15 11:04

alanbuchanan


1 Answers

How can I debug my recursion code?

First, make sure you have switched to the Debug perspective and you're seeing the correct windows (Variables, Expressions, Debug and your source code) e.g. like this:

Eclipse - debug recursion

Next, note that in Debug you can see how often the method is currently called. This list will grow and shrink depending on how many methods were called and have not returned yet.

You can click on one of the methods to change the scope. See how the contents of Variables changes when you change the scope.

Finally, to check arbitrary things, enter expressions in the Expressions window. This is almost like live coding. You can inspect virtually anything.

Am I focussing too much on debugging?

No. Learn doing it right and it will save you much time later.

Adding a System.out.println() needs to recompile and you need to reproduce the situation which is not always that simple.

like image 141
Thomas Weller Avatar answered Oct 06 '22 00:10

Thomas Weller