Q:

Difference in Recursion of ArrayList and Array

Filling up simple array recursively and then printing all contents:
void printArray(int[] a,int i)
    {
        if(i > 5)
            return;

        a[++i] = i;
        printArray(a,i);

        System.out.println("array size is "+a.length);
        for(int k=0;k<i;k++)
            System.out.print(a[k]+" ");
        System.out.println();
    }

Output : ( array size is defined in main )
array size is 6
0 1 2 3 4 
array size is 6
0 1 2 3 
array size is 6
0 1 2 
array size is 6
0 1 
array size is 6
0 

Now, take this simple ArrayList snippet :
void printArray(ArrayList a, int n)
{
    if(++n > 5)
        return;

    a.add(n);
    printArray(a,n);

    System.out.println("Size of array list is "+a.size());
    System.out.println("Content of Array list are "+a+"\n\n");
}

Output :
Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5] /*this is fine */

Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5] /*should have been [0, 1, 2, 3, 4]*/

Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5]/*should have been [0, 1, 2, 3]*/

Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5]/*should have been [0, 1, 2]*/

Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5]/*should have been [0, 1]*/

Size of array list is 6
Content of Array list are [0, 1, 2, 3, 4, 5]/*should have been [0]*/

Question : In memory implementation of Recursion stack, array output is what i understand correctly, previous or below stack holding value one less than the stack above it as i increments but using same implementation, why does all stacks of ArrayList contains value that should have been only in top of the recursion stack???
How is recursion implemented in case of ArrayList???

A:

Your code first fills up the Array respectively the ArrayList with values and then prints the content.
The only difference is that in the case of the ArrayList you print the whole list while in the case of the Array you only print elements 0 through i.
Since i is a primitive value each invocation of printArray() has its own version of it. 
But Objects, like instances of ArrayList, are passed as reference. Thus each invocation of printArray() is working on the same ArrayList and not on a copy of the original instance. That is the reason why all invocations of printArray() print the same result when using the ArrayList.
Here is a tutorial which describes the difference between primitive types and Objects: http://www.javawithus.com/tutorial/call-by-value-and-call-by-reference

