Parameter passing in Java

Keywords: Java Back-end

1. Is java value passing or reference passing?  

This is a controversial but not controversial question. If you ask, you can answer that it is value transmission. Let's learn about parameter passing in Java

 

2. What is value passing and reference passing?

Value transfer:

Value passing refers to copying and passing a copy of the actual parameters to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected. (a basic data type copies its own value, while a reference data type copies its address. Therefore, if a basic data type and a variable of a reference data type are passed into a function, the actual values outside the function of the basic data type will not be affected, and the address of the reference data will not be modified, but if the reference data type is modified The property value of the object, and the actual parameters outside the function will be affected)

        

                                                (this is the explanation above Baidu entry)

Reference passing:

Reference passing refers to passing the address of the actual parameter to the function when calling the function. The modification of the parameter in the function will affect the actual parameter.

 

                                                  (this is the explanation above Baidu entry)

3. There is only one parameter transfer method in Java, that is, value transfer

When you ask most programmers whether Java passes values or references, you may get one of two answers: (1) Java uses the value passing method when passing raw type data; When the object is passed, the reference method is used; String data adopts the value transfer method because the string is immutable. (2) All parameters passed by Java use the value passing method.

Only the second answer is correct. The key to understanding the difference between value passing and reference passing is to remember that when you pass an object to a method, Java does not put the object on the stack. It just copies the reference of the object and then puts the copy of the reference on the stack. That is, by definition, Java uses value passing.

4. Test of parameter value transfer in Java

Basic data type test:

public class train {
    public static void test(int a,int b){
        int jie = a;
        a = b;
        b = jie;
        System.out.println("Values in test method:  a Yes:"+a+",b Yes:"+b);
    }

    public static void main(String[] args) {
        int a = 10;
        int b = 11;
        test(a,b);
        System.out.println("Values in the main method:  a Yes:"+a+",b Yes:"+b);
    }
}

Operation results:

This proves that when the parameter is a basic data type, the transfer is value transfer.

Reference data class test:

public class train {
    public static void test(Test test){
        test.setA(100);
        test.setB(110);
        System.out.println("Address under test:"+test);
        System.out.println("Attribute values in the test: a: "+test.getA()+" , b: "+test.getB());
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.setA(10);
        test.setB(11);
        System.out.println("Address before test:"+test);
        System.out.println("Attribute values before test: a: "+test.getA()+" , b: "+test.getB());
        test(test);
        System.out.println("Address after test:"+test);
        System.out.println("Attribute values after test: a: "+test.getA()+" , b: "+test.getB());
    }
}
class Test{
    private int a;
    private int b;

    public Test() {
    }

    public Test(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }
}

  Operation results:

It can be seen here that reference passing is actually value passing. The passed value is the address (pointer). It is effective to change the attribute of the object through this address, which will affect the actual attribute of the object outside the function.

Relevant interview simulation:

Q: please give the running results of the following end code

public class train {

    public static void main(String[] args) {
        String name = "Scott";
        StringBuilder sb = new StringBuilder("wsq");
        int age = 5;
        User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setSb(sb);
        System.out.println("Before change: user = " + user);

        change(user, name, age,sb);
        System.out.println("After change: name = " + name);
        System.out.println("After change: age = " + age);
        System.out.println("After change: sb = " + sb);
        System.out.println("After change: user = " + user);
    }

    public static void change(User user, String name, int age,StringBuilder sb) {
        name = "Tom";
        age = 20;
        sb.append("test");
        user.setName(name);
        user.setAge(age);
        user.setSb(sb);
    }

    static class User {
        private String name;
        private int age;
        private StringBuilder sb;


        public StringBuilder getSb() {
            return sb;
        }

        public void setSb(StringBuilder sb) {
            this.sb = sb;
        }

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", sb=" + sb +
                    '}';
        }
    }
}

  My result is:

Q:

Age is a basic type variable. User, String and StringBuilder are all reference type variables. However, after calling the change() method, the argument name and age are not changed, but the sb and user objects are changed. Can we say that when the change() method is called, the user object is passed by reference and the age is passed by value? But what is the transmission method of String? Its performance is the same as that of age, but it is a reference object. How to explain this? What about StringBuilder?

Answer:

Java is different from C + +. In C + +, there is a function call mode of reference passing, while in Java, there is only value passing.

For the application scenario of the above program, when calling the change() method, the user, name, and age variables are passed values.

Among them, the user object copies a reference, and the reference is the address of the object. The modification of the user in change() does not affect this address, but modifies the object properties. The key to confusion is that when people see that the object itself is modified by the function, they mistakenly think that it is reference passing. But the key to distinguish between value passing and reference passing is whether the argument is modified by the function. For the user object, the address is the argument! However, if you modify the address referenced by user in the change() method, that is, create a new user object, you will see that the user in the main method has not changed, which proves that it is actually value passing.

The name variable naturally copies a name reference and passes it to the change() method. According to the definition of value passing, the function's modification of this copy will not affect the actual parameters. Also, because of the final feature of String, name = "Tom"; In fact, the address of name is modified, so the actual parameters will not be affected by the function modification.

age itself also passes a copy of the value into change(), so any modification will not affect the argument. So we say that in Java, there is only one parameter passing method, value passing.

(I'll leave you to think about StringBuilder here!)

Add a question:

When the output result of the above code is, can it be regarded as reference passing?

Posted by seanrock on Fri, 05 Nov 2021 21:37:34 -0700