title: Passing Stack to a function
body: <p>I am trying to solve a question on hackerrank.But I keep getting <strong>emptyStack exception</strong> every time.I think it might be because i am passing the stack to getMax function and it is changing the original stack.<br />
  I tried to write this in getMax hoping maybe it won't affect the final stack,but it didn't work.</p>
  <pre><code>Stack&lt;Integer&gt; s=st;
  </code></pre>
  <p>Can you point out and explain the mistake I am making.</p>
  <ul>
  <li><p>The program is running perfectly fine for some test cases.(0,2,27)</p>
  </li>
  <li><p><strong>Question Link</strong> : <a href="https://www.hackerrank.com/challenges/maximum-element/copy-from/243724938" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/maximum-element/copy-from/243724938</a></p>
  </li>
  <li><p>My solution:</p>
  <pre><code>import java.util.*;
  class Solution
  {
  static void getMax(Stack&lt;Integer&gt; st)
  {
   Stack&lt;Integer&gt; s=st;
   int max=s.peek();
   s.pop();
   while(!s.empty())
   {
       if(s.peek()&gt;max)
       max=s.peek();
       s.pop();       
   }
   System.out.println(max);
   }
   public static void main(String args[])
   {
   Stack&lt;Integer&gt; s=new Stack&lt;Integer&gt;();
   Scanner sc=new Scanner(System.in);
   int n=sc.nextInt();
   while(n--&gt;0)
   {
       int c=sc.nextInt();
       if(c==1)
       s.push(sc.nextInt());
       else if(c==2)
       s.pop();
       else
       getMax(s);
   }        
   } 
  }
  </code></pre>
  </li>
  </ul>
  <p><img src="https://i.stack.imgur.com/mrjAU.png" alt="ONE OF ERROR GIVING TEST CASE" /></p>