Java exchange values for two variables
1. Kindergarten Edition
PackageTST; Public classtest{ Public Static voidMain (string[] args) {String x= "XX"; String y= "YY"; Exchange (x, y); System.out.println (); SYSTEM.OUT.PRINTLN (x+ "<->" +y); } Private Static voidExchange (String A, string b) {String temp=A; A=b; b=temp; System.err.println (A+ "<->" +b); System.err.println (); }}
Obviously, this is wrong.
Just from this version.
There is only one way to pass the parameter of the 1.java method: The value is passed, that is, a copy of the actual parameter value is passed in the method, and the parameter itself is unaffected.
(Do you feel like you already know why the above procedure is wrong)
When you call the Exchange method in the 2.main method, the main method is not finished, so main and exchange allocate two zones.
So the real exchange is actually only in the exchange stack, and the main stack does not change
Look at the right version again.
PackageTST; Public classtest2{ Public Static voidMain (string[] args) {peoplename pname=NewPeoplename (); Pname.firstname= "First"; Pname.lastname= "Last"; Swap (pname); System.err.println (Pname.tostring ()); } Private Static voidswap (Peoplename p) {String temp=P.firstname; P.firstname=P.lastname; P.lastname=temp; SYSTEM.OUT.PRINTLN (P); }}classpeoplename{ PublicString FirstName; PublicString LastName; @Override PublicString toString () {return"Peoplename [firstname=" + FirstName + ", lastname=" +LastName+ "]"; }}
When an object is created, there are two entities in memory: the object itself is saved in the heap memory, and the reference to the object is stored in the stack.
This is not the case before calling swap.
When called
Because of the value passing, the line of swap is also a reference to the heap, so that he can manipulate the heap,
That makes sense.
Expand
Replication of objects
Peoplename P1 = new Peoplename ();
P1.firstname = "QQ";
P1.lastname = "WW";
Peoplename P2 = p1;
P1.firstname = "ee";
At this point the FirstName attribute of P1,P2 is "EE" for the same reason
The last very common scenario is to take the object from Resutlset, whether the object should be initialized outside the loop, or the initial UA problem in the loop, the answer is inside (prompting the initialization of new to allocate memory)
The reason is ditto
1. Method of transfer mechanism
Storage and reference of variables in Java