Java basics of value transfer

@author: Tobin
limited, if wrong, please correct me hope.
Reference "Java core technology volume - Basics 10th edition of"
binding Bowen: https: //juejin.im/post/5bce68226fb9a05ce46a0476, its summary.

First, ask yourself what is passed by reference, what is the value passed?
Value is passed: pass a copy of the method to invoke a method of changing the copy of the value, but does not change the original value
passed by reference: passing the object (or variable) reference, modify it, it will change the original value.

From the perspective of memory allocated to explain the Java transfer value only exists, transmitting reference does not exist .
The use of Java in the method parameters.
1. a method can not modify the basic data types of the parameters.
The reason is that the main method parameters such as basic data type parameter, is in its own stack frame, when calling a method, accordingly to establish a new stack frame memory, copies the incoming parameters, modifications are also made to call the method only for parameters for the copy, when leaving the functions, methods, stack frame is destroyed, modified parameter are also destroyed. Back to the main stack frame, the original variable has not been modified. You can see below this chart to understand.

2. A method may change the state of a parameter of the object.
Below this figure, it is a per object whose value is the address of an area (of course, in c ++ pure and address are different). This address points to an area in the stack area. Creating new objects are stored on the heap. When we create an object, is really two steps.

Employee per;
per=new Employee();

第一步就是虚拟机栈中分配的区域,第二步就是在堆中分配区域。
如何理解没有引用传递呢?我们知道如果传入的参数是对象,方法对对象的修改会改变原来的对象值。原因在于,我们传入的参数per,此时依然是拷贝了新的变量放在方法栈帧中,它和原来的per值是相同的,但是对它进行修改,其实是对指向的堆中元素修改。堆是共享的,并不会随着方法栈帧的销毁而销毁。所以per的值就会被改变。
所以在java中无论是对象参数还是基本类型参数,它们的传递就是拷贝新的值,是值传递。
下面这段代码,进一步验证了对象参数是值传递,a,b对象并没有交换它们所指的对象,因为传入的参数仅仅是它们值得拷贝,换句话说它们的值并没有被改变,但是如果改变指向的堆区的状态是可以的。

public static void swap(Employee x , Employee y) // doesn't work
    Employee temp = x;
    x = y;
    y = temp;
} 
Employee a = new Employee("Alice", . . .);
Employee b = new Employee("Bob", . . .);
swap(a, b);
// does a now refer to Bob, b to Alice? 

这点和C++不同,C++是有引用传递的。
综上,即使改变了指向的堆的状态,原来的对象对应的地址值也并没有被修改。根据开始时所说的引用传递的定义,我们可以得到结论,Java中只有值传递,并没有引用传递。这就造成了直接swap(a,b)是无法交换两个变量的值的。知道这个结论后,我们应该明白有些操作是做不了的,而不是死记概念。

下面这幅图展现了Java程序的加载与存储,原博讲解的不错,注意一下可以看到static方法是存放在一个特定的区域的,它不属于对象,属于类。

Guess you like

Origin www.cnblogs.com/zuotongbin/p/11091026.html