I know the difference between pass by value and pass by reference. But while coding a logic I found it to be not completely clear.
Below is the code that I tested with a reference type arr
, primitive int i
and an object root
of type Node(user defined).
static void recursiveFn(int[] arr, Node root, int i, int times) {
if(times > 3)
return;
if(times == 2) {
arr[0] = 1;
i = 1;
root = root.next;
}
times++;
recursiveFn(arr, root, i, times);
System.out.println(times+" - "+arr[0]+" "+i+" "+ root.data);
}
The output was:
4 - 1 1 1
3 - 1 1 1
2 - 1 0 0
1 - 1 0 0
The index zero of the array persists in the call stack while the control go backs to the previous recursive call - This is what pass by reference mean.
The int i produced its current value at respective function call.
I didn't understand why the root being an object didn't persists its value through out the recursive call.