-2

Why doesn't the variable inside the function update but when I print it outside it, it doesn't work. But if I do the same with ArrayList, the ArrayList gets updated. Why So???

public int perfectSum(int arr[],int n, int sum) 
    { 
        // Your code goes here
        int i = 0;
        helper(arr,sum,0,0,i);
        return i;
    } 
    void helper(int arr[], int target, int sum, int idx, int i){
        if(idx == arr.length){
            if(sum == target){
                i++;
            }
            return;
        }
        
        helper(arr, target, sum+arr[idx], idx+1, i);
        helper(arr, target, sum, idx+1, i);
    }
trincot
  • 317,000
  • 35
  • 244
  • 286
Hode X
  • 1
  • "Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed." arraylist is an object. – sittsering Jul 29 '21 at 20:46
  • "if I do the same with ArrayList, the ArrayList gets updated"—The same with an arraylist would be calling `++` on an arraylist, which would not compile. But if you reassigned an arraylist variable, you would observe the same thing you do with the int variable, which is that **updating a local variable in one method does not alter a local variable in another method**. – khelwood Jul 29 '21 at 21:11

1 Answers1

0

You need to understand the difference between primitive types and reference types, when you create an array the variable you define only contains an address to the actual object in heap where if you created a primitive type you store the actual value in it.

For both int and int[] you are taking a copy of the content of the variable, but for array case you got a copy of the address so you can manipulate the object and change the actual object in heap.

Diya'
  • 78
  • 6