Java – Changing the values of variables in methods, Java

javascope

I have a question about changing the values of variables in methods in Java.

This is my code:

public class Test {
    public static void funk(int a, int[] b) { 
        b[0] = b[0] * 2; 
        a = b[0] + 5;
    } 

    public static void main(String[] args) {
        int bird = 10;
        int[] tiger = {7};

        Test.funk(bird, tiger);
    }
}

After the execution of the method Test.funk(bird, tiger), the value of bird is not changed – it remains with the value 10, even though in the funk() method we have changed the value with a = b[0] + 5;

On the other hand, the value of the element in the array changes, because we have the statement b[0] = b[0] * 2;

I don't understand why one thing changes and the other not? Could someone please explain this for me.

Best Answer

Look at Jon Skeet's article about Parameter-Passing in Java, which explains this.

In short (look at his site for a more throughout explanation):

Arrays are reference types. If you pass a reference that points to an array, the value of the reference is copied and assigned to the parameter of the function. So the parameter will point to the same array as the argument that was passed. Thus changes you make to the array through the parameter of your function will be visible in the calling function. Changing the parameter itself (b), for example by setting it to null, however, will not be noticed by the calling function, since the parameter (b) is just a copy of the argument (tiger) passed.

Integers are so-called primitive types. Passing the integer copies its value and assigns it to the parameter too. But that value is not a reference to the actual data, but is the data itself. So changes to the paramter in the function will affect the parameter (a), but not the argument passed in the calling function (bird).