Java value passing and reference passing

When an object is passed as a parameter to a method, the method can change the properties of the object and return the changed results. Is this value transfer or reference transfer? A: it is value transfer. The Java programming language has only value passing parameters. When an object instance is passed to a method as a parameter, the value of the parameter is a copy of the reference to the object. Pointing to the same object, the content of the object can be changed in the called method, but the reference of the object (not a copy of the reference) will never change.

Java parameters, whether original types or reference types, pass copies (there is another way to say that value transfer, but it is better to say that copy transfer is better understood. Value transfer is usually relative to address transfer).

If the parameter type is the original type, a copy of the parameter, that is, the value of the original parameter, is passed. This is the same as the value passed before. If you change the value of the copy in the function, the original value will not be changed.

If the parameter type is a reference type, a copy of the reference parameter is passed, and the copy stores the address of the parameter. If the address of this copy is not changed in the function, but the value in the address is changed, the change in the function will affect the incoming parameters. If the address of the copy is changed in the function, such as new, the copy points to a new address. At this time, the passed in parameter still points to the original address, so the value of the parameter will not be changed.

Example:

Display results:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>