Value is passed, there is only Java code sample

package copy;

/**
 * @Author Snail
 * @Describe 值 引用传递代码示例  ,Java中,只存在值传递
 * @CreateTime 2019/8/3
 */
public class ValueReferencePassing {
    public static void main(String[] args) {
        int i1=111111111;
        int i2=222222222;
        //Java中,只存在值传递
        swap(i1,i2);
        System.out.println("i1="+i1+"    i2="+i2);//i1=1111111111    i2=222222222

//////////////////////////
        int[] arr = { 1, 2, 3, 4, 5 };
        System.out.println(arr[0]);//   1
        change(arr);//此处传递的是,arr在虚拟机栈中的引用,引用指向堆中的具体数组
        System.out.println(arr[0]);//   0
///////////////////////
        Person p1=new Person("p1 name");
        Person p2=new Person("p2 name");
        swap(p1,p2);    //对对象的传递也是 值传递
        System.out.println("  p1:" + p1.getName()+"    p2:" + p2.getName()); // p1:p1 name    p2:p2 name

        swapValue(p1,p2);    //对对象的传递也是 值传递
        System.out.println("  p1:" + p1.getName()+"    p2:" + p2.getName()); //  p1:p2 name    p2:p1 name
    }
    public static void swapValue(Person x, Person y) {
        //x和y都是虚拟机栈中的引用,但对name的操作影响到了引用指向的堆中内容
        String temp = x.getName();
        x.setName(y.getName());
        y.setName(temp);
        System.out.println("x:" + x.getName()+"    y:" + y.getName());
    }
    public static void swap(Person x, Person y) {
        //x和y都是虚拟机栈中的引用
        Person temp = x;
        x = y;
        y = temp;
        System.out.println("x:" + x.getName()+"    y:" + y.getName());
    }
    public static void change(int[] array) {
        array[0] = 0;//此处的array[0]是对数组中0号元素的引用
    }
    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;

        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
class Person{

    private  String name;
    public Person(String name){
        this.name=name;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

 to sum up:

Java is only passed by value, but the value of specific virtual machine stack and heap references in memory, causing some misunderstanding of the value passed.

The JVM Related reference: https://blog.csdn.net/BigBug_500/article/details/90313130

Copy depth VM stack, the stack may refer to: https://blog.csdn.net/BigBug_500/article/details/93381273

 

Published 91 original articles · won praise 54 · views 10000 +

Guess you like

Origin blog.csdn.net/BigBug_500/article/details/98360906