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 n
th 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:
return fibonacci(n - 1) + fibonacci(n - 2)
is simple to understand?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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With