All recursive methods have three things:
- An exit condition, to prevent an endless loop
- A work item, and
- A recursive call.
The exit condition in your recursive function is:
if (n == k)
return;
The work item is:
n++;
System.out.println(n + " " + k);
Unless k is greater than n, in which case the work item is:
k--;
System.out.println(n + " " + k);
The recursive call is:
recTest (n,k);
Note that, since a return early-exits you out of the method, the else statement is not required.
To understand the behavior of a recursive method, you must first understand what a stack frame is, how the stack works, and how it serves to preserve state between method calls.
When Java prepares to call a method, it puts the calling methods' local variables including its parameters (collectively, the method's "state") and the return address of the calling method into a stack frame, and pushes that stack frame onto the stack. It then calls the new method.
When Java returns from a method, it pops the stack frame off the stack, restoring the calling method's original state.
A stack is like the stack of plates you see in the carousel at a 50's diner; the first plate off the stack is the last plate the dish washer put there. We call this a last-in, first-out (LIFO) queue.
With a little imagination, you can see how successive calls to a recursive method will keep a running history of any changes made to the state during each recursion. Since a copy of the state is saved during each recursion, you can walk back to a previous step in the state by returning from a method call.