Parameter passing of Java methods (value passing and reference passing)

Method is meaningful only when it is called by its class or object. If the method has parameters:

Formal parameter: parameter of method declaration;

Argument: the parameter value actually passed to the formal parameter during method call;

How can Java arguments be passed into methods?

First of all, it should be clear that variables are divided into two categories: basic data type and reference data type.

There is only one basic data type parameter transfer method: value transfer. That is, a copy (Replica) of the actual parameter value is passed into the method, and the parameter itself is not affected;

Output: 6 2

Note: in other words, I in test method and I in main method are not the same I, and their addresses in memory are different. In short, in the process of passing parameters, the basic data type first assigns the value of the argument to the formal parameter, and then opens up a memory in the stack to assign the value to a new variable.

The reference data type parameter is passed. Both the original instantiated object and the newly created instantiated object point to the same object. Therefore, the change of the reference object value will affect the new object.

DataSwap. java

Test. java

Output: 0 6

Note: when instantiating DS, the member variable a is given an initial value of 0, and then the DS object is passed to the formal parameter DS1. At this time, although DS and DS1 have their own addresses in the stack memory, they both point to the same object dataswap, and then changing the value of a through the DS1 object actually changes the value of the dataswap object, so it will also affect other instantiated objects, Therefore, the final output is 0 6.

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
分享
二维码
< <上一篇
下一篇>>