title: Java recursion class variable value is reset to 0
body: <p>I was trying to implement the coin change problem using recursion. I have written the following code and am facing a problem with the static class variable. 'answer' is a class variable and i am trying to add the return value to it in the loop. This works fine within the while loop but after the while loop ends the answer is reset to 0;</p>
  
  <pre><code>    while (i * currentCoin &lt;= sum) {
      System.out.println("inside while; answer is " + answer);
            answer = answer
              + findCombinations(
                      sum - i * currentCoin,
                      new ArrayList&lt;Integer&gt;(denominations.subList(1,
                              denominations.size())));
      i++;
  
  }
  </code></pre>
  
  <p>Below is all the code that I have written. You can copy and run it to check.</p>
  
  <pre><code>    import java.util.ArrayList;
      import java.util.Collections;
  
      public class CoinChangeHashMap {
  static int answer = 0;
  
  public static void main(String[] args) {
  
      int[] array = new int[] { 7, 3, 2 };
      ArrayList&lt;Integer&gt; input = new ArrayList&lt;Integer&gt;();
      getList(array, input);
      findCombinations(12, input);
      System.out.println(answer);
  }
  
  private static void getList(int[] array, ArrayList&lt;Integer&gt; input) {
  
      for (int i : array) {
          input.add(i);
      }
  
  }
  
  public static int findCombinations(int sum, ArrayList&lt;Integer&gt; denominations) {
  
      if (denominations.size() == 1) {
          if (sum % denominations.get(0) == 0) {
              return 1;
          }
          return 0;
  
      }
      int i = 0;
      int currentCoin = denominations.get(0);
  
      while (i * currentCoin &lt;= sum) {
          System.out.println("inside while; answer is " + answer);
  
          answer = answer
                  + findCombinations(
                          sum - i * currentCoin,
                          new ArrayList&lt;Integer&gt;(denominations.subList(1,
                                  denominations.size())));
          i++;
  
      }
      return 0;
  }}
  </code></pre>
  
  <p>**The output that I get is 0. but the expected output is 4. While debugging the output that I got is **</p>
  
  <pre><code>inside while; answer is 0
  inside while; answer is 0
  inside while; answer is 1
  inside while; answer is 1
  inside while; answer is 2
  inside while; answer is 2
  inside while; answer is 0
  inside while; answer is 0
  inside while; answer is 0
  0
  </code></pre>
  
  <p>Any Help is appreciated.</p>