Reference passing and value passing

   Value transfer (pass by value) refers to when calling function copies the actual parameters passed to a function, so if modify parameters in functions will not affect the actual parameters.
   Passed by reference (pass by reference) means that when you call the function directly address the actual arguments passed to the function, then to modify the parameters carried out, it will affect the actual parameters in functions.
   Only value is passed in JAVA, no reference is passed. The address value is also a value, and passing the address value is not necessarily just passing by reference. The difference between value passing and reference passing is not what is passed. It is whether the actual parameter is copied to the formal parameter. In C language, there is such a statement as reference transfer, but in JAVA, although there is a similar effect, there is essentially no reference transfer. The effect of similar reference transfer we have seen is essentially value transfer.
   The basic type variables such as int boolean char float double and other basic types have their data stored in the stack after being defined. Then the basic type variable is only passed a value when it is passed. The new variable itself has no other relationship except the value and the prototype are consistent. So the basic type variable transfer is value transfer.
  For these encapsulated types of String Integer, passing str in the past is actually equivalent to

String str=“hello”;
String st=str;

The value of "address" is passed here, so st = str just assigns the address pointed to by str to st. It stands to reason that since st and str share a common address, then str should also change when st changes, so why the original variable str No change yet. This involves the source code of the encapsulated classes such as String and Integr. Look at the underlying implementation of Stirng.

private final char value[];  

value is a final constant that cannot be changed, and there is no set method in the source code, which means that once the value cannot be modified, it means that we usually modify the value is actually equivalent to a new space in the heap , A new String object is created, and then the pointer of the variable is modified to point to the new object, so the value changes.
  However, when defining a class, member variables are rarely defined as final and the set method is not set, so the pointer of the heap is passed when the custom class is passed, and the member variable is changeable. Then the effect is reference. Transfer effect (although the essence is value transfer).

java只有值传递的。
如果是基本数据类型,传递的就是实际的值。
如果是引用数据类型,传递的就是该引用的地址值。
Published 162 original articles · praised 58 · 90,000 views

Guess you like

Origin blog.csdn.net/ThreeAspects/article/details/105615118