title: Tracing recursive calls in java?
body: <p>How do recursive calls work with stacks? I have this sample code in which line <code>B</code> prints  <code>B 654321</code>, <code>c</code> prints <code>C</code>, <code>d</code> prints  <code>D 2468</code> and <code>e</code> throws an exception. I do not understand why the program is printing those outputs! For instance, in line B, doesn't <code>s</code> become <code>0</code> as a result of the stack? Thank you</p>
  
  <pre><code>public class Problem1 { 
  public static void main(String args[]) { 
      Stack&lt;Integer&gt; s = setStack(5); printStack("A",      s); // line A 
      s = setStack(6); stackStack(s); printStack("B", s); // line B 
      s = setStack(8); cutStack(s); printStack("C", s); // line C 
      s = setStack(8); s = cutStack(s); printStack("D", s); // line D 
      s = setStack(7); s = cutStack(s); printStack("E", s); // line E 
  } 
  public static Stack&lt;Integer&gt; setStack(int n) {     
    Stack&lt;Integer&gt; ans = new Stack&lt;&gt;(); 
      for (int i = 1; i &lt;= n; i++) 
          ans.push(i); 
      return ans; 
      }
  public static void printStack(String tag, Stack&lt;Integer&gt; s) { 
    System.out.print(tag + " "); 
    while (!s.empty()) System.out.print(s.pop());    
    System.out.println(); 
   } 
  public static Stack&lt;Integer&gt; cutStack(Stack&lt;Integer&gt; s)  
    { 
    Stack&lt;Integer&gt; ans = new Stack&lt;&gt;(); 
    while (!s.empty()) { 
       ans.push(s.pop()); 
       s.pop();
    } 
    s = ans; return s;
  } 
  public static void stackStack(Stack&lt;Integer&gt; s) { 
     if (s.empty()) return; 
     int x = s.pop(); 
     stackStack(s); 
     s.push(x); 
  }
  }
  </code></pre>