About the value and pass the reference to see a lot of posts, a lot of fallacy, even some people have not tested directly guess the results written blog, fraught, really let people angry!
The reason many people make mistakes on this issue is that they are actually not understanding the formal parameters.
The formal parameter of a method is only valid in this method, and as the method is pop in the method stack frame, all the formal parameters are waiting to be garbage collected.
For example, we have code like this:
Public Static voidMain (string[] args) {test test=NewTest (); String a=" One", b=" A"; Test.swapposition (A, b); System. out. println (a); System. out. println (b); } Private voidswapposition (String A, string b) {string T=NULL; T=A; A=b; b=T; }
The output result is 11, 22;
Then replace the string type with an integer type:
Public Static voidMain (string[] args) {test test=NewTest (); Integer a= One, b= A; Test.swapposition (A, b); System. out. println (a); System. out. println (b); } Private voidswapposition (integer A, integer b) {integer T=0; T=A; A=b; b=T; }
The result is still 11, 22;
Some people say that you change the object to a basic type, and the result is that the reference becomes the value of the pass.
Then the author pro-Test:
Public Static voidMain (string[] args) {test test=NewTest (); intA = One, b= A; Test.swapposition (A, b); System. out. println (a); System. out. println (b); } Private voidSwapposition (intAintb) { intt =0; T=A; A=b; b=T; }
The result is still output is 11, 22 will not change at all;
In fact, you can understand it in a different way:
Public Static voidMain (string[] args) {test test=NewTest (); intA = One, b= A; Test.swapposition (A, b); System. out. println (a); System. out. println (b); } Private voidSwapposition (intXintFY) { intt =0; T=x; X=y; Y=T; }
In fact, no matter how you operate, the operation is the formal parameter x, y, then how to achieve the exchange position? There is only one answer: bypass the formal parameter and do not use an extra method:
Public Static void Main (string[] args) {intOne, b=;
int t = 0;
T =a;
A = b;
B = t; System. out . println (a); System. out . println (b); }
Then the output value is 22,11
Java value and pass-through references