title: Behaviour of an array when passed as a parameter in recursive calls
body: <p>I thought I understood the concept of pass by value and reference in Java. But I just found out that I don't. </p>
  
  <p>Below are two methods that are being recursively called. In the first method, I am passing an array in the recursive calls, from top to bottom. When the condition is met, it prints the array and then returns. As the recursive calls return, the elements added to the array are removed with the return from each level.  </p>
  
  <p>But if I use an <code>ArrayList</code>, the additions of elements to the list is permanent, even after all the recursive calls return. </p>
  
  <p>I assumed that in both cases, I am passing the array and <code>Arraylist</code> by reference (copy of reference) and I'm directly modifying the array. So whatever changes i make in the array, shouldn't it remain after the method returns? Please suggest, where am I getting it wrong.</p>
  
  <p>I have not added the <code>print()</code>, I guess its evident from the output.</p>
  
  <pre><code>static void recurse(int[] list, int num) {
      if(num == 5) {  // print if condition is true
          print("Reached num = 5", list, num); 
          return;
      }
      list[num] = num;
      recurse(list,num+1);
      print("After recursive call returns ", list, num);// check elements in array
  }
  
  static void recurse(ArrayList&lt;Integer&gt; list, int num) {
      if(num == 5) {  // print if condition is true
          print("Reached num = 5", list); 
          return;
      }       
      list.add(num);
      recurse(list,num+1);
      print("After recursive call returns ", list); // check element of Arraylist
  }
  private static void print(String msg, ArrayList&lt;Integer&gt; list) {
      System.out.println(msg);
      System.out.println(list);       
  }
  private static void print(String msg, int[] list, int index) {
      System.out.println(msg);
      for(int i = 0 ; i &lt; index; ++i)
          System.out.printf("%d ", list[i]);
      System.out.println();       
  }
  
  public static void main(String[] args) {
      ArrayList&lt;Integer&gt; arr1 = new ArrayList&lt;&gt;();
      recurse(arr1,0);
      int[] arr2 = new int[12];
      recurse(arr2,0);
  }
  </code></pre>
  
  <p>Output from First</p>
  
  <pre><code>Reached num = 5
  0 1 2 3 4 
  After recursive call returns 
  0 1 2 3 
  After recursive call returns 
  0 1 2 
  After recursive call returns 
  0 1 
  After recursive call returns 
  0 
  After recursive call returns
  </code></pre>
  
  <p>Output from second</p>
  
  <pre><code>Reached num = 5
  [0, 1, 2, 3, 4]
  After recursive call returns 
  [0, 1, 2, 3, 4]
  After recursive call returns 
  [0, 1, 2, 3, 4]
  After recursive call returns 
  [0, 1, 2, 3, 4]
  After recursive call returns 
  [0, 1, 2, 3, 4]
  After recursive call returns 
  [0, 1, 2, 3, 4]
  </code></pre>