About Java reference
After reading a few articles introducing Java references, it seems that there is no graphic to explain, and some readers (including the beginning of me), the more it is, more passed. Currently, a number of combined articles, I hope everyone will give more comments.
Procedures for this article:
Public class example {
Private Static Void Swap (StringBuffer S1, StringBuffer S2) {
S1.Append ("append");
StringBuffer T;
T = S1;
S1 = S2;
S2 = T;
}
Public static void main (String [] args) {
StringBuffer SB1 = New StringBuffer ();
StringBuffer SB2 = new stringbuffer ();
sb1.append ("sb1");
SB2.Append ("sb2");
SWAP (SB1, SB2);
System.out.println (SB1);
System.out.println (SB2);
}
}
The output is:
SB1Append
SB2
The value of SB1 is changed in method SWAP (), and the parameters passing are referenced by SB1. What is the exchange of SB1 and SB2? The following will be explained below.
(1) See Figure 1. There is no calling and stack before the method swap (), and the connection between the stacks and stack represents reference (or points)
figure 1
(2) The method swap () is called, but the instructions in SWAP () have not yet implemented. See Figure 2
figure 2
(3) Execute S1.Append ("append"); StringBuffer T; See Figure 3
image 3
(4) T = S1 is executed. See Figure 4
Figure 4
(5) S1 = S2 is executed. See Figure 5
Figure 5
(6) Execute S2 = T; See Figure 6
;
Figure 6
(7) Method SWAP () is called, and after returning to method main (). See Figure 7
Figure 7
From the above, it can be seen that S1 and S2 are exchanged, and SB1 and SB2 are not exchanged.