title: Dynamic Stack : Java
body: <p>Can anyone explain, why does the value of <strong>'tos'</strong> variable change as diplayed in the stacktrace?</p>
  
  <p>Following is the code for DynamicStack.java:</p>
  
  <pre><code>public class DynamicStack{
  private int stck[];
  int tos;
  
  DynamicStack(int size){
      stck = new int[size];
      tos = -1;
  }
  
                     // Following push method implements growable stack.
  public void push(int item){
      if(tos == stck.length-1){
          int temp[] = new int[2*stck.length];    
          for(int i=0; i &lt; stck.length; i++) temp[i] = stck[i];
          stck = temp;
          stck[++tos] = item;
      }
  
      else
          stck[++tos] = item;
  }
  
  
  public int pop(){
      if(tos &lt; 0) {
          System.out.println("Stack underflow");
          return 0;
      } else return stck[tos--];
  }}
  </code></pre>
  
  <p>Following is the code for Test_Dynamic_Stack.java:</p>
  
  <pre><code>public class Test_Dynamic_Stack{
  public static void main(String a[]){
      DynamicStack mystack1 = new DynamicStack(5);
      DynamicStack mystack2 = new DynamicStack(8);
  
      for(int i=0;i&lt;7;i++) mystack1.push(i);
      for(int i=10;i&lt;20;i++) mystack2.push(i);
  
      System.out.println("In mystack1");
      for(int i=0; i&lt;7; i++) {
          System.out.println("Mystack1: "+mystack1.pop());
          System.out.println("Mystack2: tos = "+mystack1.tos);
      }
  
      System.out.println("In mystack2");
      for(int i=0; i&lt;10; i++) {
          System.out.println("Mystack2: "+mystack2.pop());
          System.out.println("Mystack2: tos = "+mystack2.tos);
      }
  }
  }
  </code></pre>
  
  <p>Following is the stacktrace:</p>
  
  <p><code>In mystack1
  Mystack1: 6
  Mystack2: tos = 5
  Mystack1: 5
  Mystack2: tos = 4
  Mystack1: 4
  Mystack2: tos = 3
  Mystack1: 3
  Mystack2: tos = 2
  Mystack1: 2
  Mystack2: tos = 1
  Mystack1: 1
  Mystack2: tos = 0
  Mystack1: 0
  Mystack2: tos = -1
  In mystack2
  Mystack2: 19
  Mystack2: tos = 8
  Mystack2: 18
  Mystack2: tos = 7
  Mystack2: 17
  Mystack2: tos = 6
  Mystack2: 16
  Mystack2: tos = 5
  Mystack2: 15
  Mystack2: tos = 4
  Mystack2: 14
  Mystack2: tos = 3
  Mystack2: 13
  Mystack2: tos = 2
  Mystack2: 12
  Mystack2: tos = 1
  Mystack2: 11
  Mystack2: tos = 0
  Mystack2: 10
  Mystack2: tos = -1</code></p>
  
  <p>Finally, got the output.. :)</p>