Say first conclusion

Method parameters are passed by value in Java. If the argument is of a primitive type, a copy of the literal value of the primitive type is passed. If the parameter is a reference type, a copy of the heap address value of the object referenced by the parameter is passed.

Let me give you another example

The base type is passed as a parameter

Public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) { System.out.println("before change , num = " + num);
    changeData(num);
    System.out.println("after change , num = " + num);
}
public static void changeData(int num) {
    num = 10;
}
Copy the code

The output is

before change , num = 2
after change , num = 2
Copy the code

This example shows that when a basic data type is passed as a parameter, it is worth copying. No matter how much you change the copy, the original value will not change.

Object is passed as a parameter

Public static void main(String[] args) {// pass A A = new A("hello");
    System.out.println("before change , a.str = " + a.str);
    changeData(a);
    System.out.println("after change , a.str = " + a.str);
}

public static void changeData(A a) {
    a.str = "hi"; } class A { public String str; public A(String str) { this.str = str; }}Copy the code

The output is

before change , a.str = hello
after change , a.str = hi
Copy the code

As a result, object A has been changed. Is the object itself passed in when the changeData method is called? The answer is no. The program starts with the main method, creating an A object and defining an A reference variable to point to the A object.


TODO

What is the output of the following program?

public class JavaDemo {

    public static void main(String[] args) {
        
        String str = new String("ada");
        char[] ch = { 'a'.'b'.'c' };

        change(str,ch);

        System.out.print(str +" and ");
        System.out.print(ch);
    }


    public static void change(String str, char ch[]) {
        str = "ada 111";
        ch[0] = 'd'; }}Copy the code