Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does array changes in method?

Tags:

java

arrays

When I write like this:

public class test {

    void mainx()
    {
        int fyeah[] = {2, 3, 4};
        smth(fyeah);
        System.out.println("x"+fyeah[0]);
    }

    void smth(int[] fyeah)
    {
        fyeah[0] = 22;
    }
}

It prints x22;

When I write like this:

public class test {

    void mainx()
    {
        int fyeah = 5;
        smth(fyeah);
        System.out.println("x"+fyeah);
    }

    void smth(int fyeah)
    {
        fyeah = 22;
    }
}

It doesn't print x22, but prints x5.

Why, in the second version function, doesn't the value change? Does it change values only for array elements?

like image 242
good_evening Avatar asked Aug 19 '11 21:08

good_evening


2 Answers

The fyeah variable in your first example contains a reference to an array (not an array), while the fyeah integer in your second example contains an integer.

Since Java passes everything by value the following will happen:

In the array case: A copy of the array reference will be sent, and the original array will be changed.

In the int case: A copy of the integer will be changed, and the original integer will not be changed.

like image 83
aioobe Avatar answered Sep 20 '22 14:09

aioobe


It's because your int is a primitive and the method smth creates a local copy which is why it doesn't print the way you want. Objects are passed by value as well, but a value to the pointer in memory. So when it is changed, the pointer stays throughout both methods and you see the change. Read More Here

like image 36
Dan W Avatar answered Sep 19 '22 14:09

Dan W