The parameter passed by the java function must be the value!

For the parameter passing of Java functions, in Java, only values ​​are passed.
Ordinary and easy to understand, like int, double type, the value passed into the function must be a value.

But for the passing of Java objects, how do you understand that what is passed is a value?
Actually, the function parameters of Java objects are passed by reference, which is actually the memory address where the object is located, which is to copy the memory address where the object is located to a temporary variable and pass in the function.

Therefore, within the function, various methods of the object can be called based on this reference.
But if you modify this reference, it will definitely have no effect on the original object.
for example:

public class Main {
    
    

    public static void main(String[] args) {
    
    
        String a="aaa";
        changTest(a);
        System.out.println(a);
    }

    static void changTest(String s){
    
    
        s="haha";
    }
}

Do you think that the changTest function can modify the content of a string?
It must not work, so the content of the output a must be "aaa".

Because when the changeTest function is called, the value is passed to the function, that is, the address of the String object is passed to s.
Then inside the changTest function, s points to a new object "haha".
But this process has no effect on the original a object.
the above.

Guess you like

Origin blog.csdn.net/xiaohaigary/article/details/113396491