简体   繁体   中英

Can't find out with output of this java code

Could anybody explain to me why the output of this code is as follows?

0 40
0 40

public class Class extends Main {

    public static void main(String[] args) {
        int x = 0;
        int [] arr = {20};
        f (x, arr);
        System.out.println(x + " " + arr[0]);
        g (x, arr);
        System.out.println(x + " " + arr[0]);
    }

    public static void f(int x, int[] arr) {
        x += 30;
        arr[0] = 40;
    }

    public static void g(int x, int[] arr) {
        x = 50;
        arr = new int[] {60};
    }

}

I thought that it should be like this:

0 20
0 20

An array is an object, so when you pass it to a method, you are passing a reference to that object. Therefore, the method call can change the elements in the array, and the array that gets changed is the same array that was passed to the method. Therefore the caller of f() sees those changes.

When you pass primitive values to a method, on the other hand, a copy of the variables is created, and any changed done by the method is local to the scope of the method. This is also true when the method receives a variable holding an object reference and tries to assign a new reference to it. That assignment is local to the method. That's why g() doesn't change the array passed to it.

So during your call to f() method, you are passing array object reference as a value to f method , So you have access to a[0] and you are allowed to change it to any value which is what you are doing and hence you get 30.

Now when you call g() method, you do pass again the reference of array object as a value and internally you try to assign new instance to array, this is perfectly valid and you would see the change that you expect within that method, but when you return back to main, you see same old reference (remember we passed reference as a value rather than original object's reference) and hence you end up seeing old 40 as value.

在Java中,数组是一个对象,对象通过引用传递,因此当您在方法中对数组进行更改时,它也会影响实际的数组

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM