This article can be used as a learning note for the Java course in Beijing Academy.
Look at the code below.
class BirthDate {private int day; private int month; private int year; Public BirthDate (int d, int. m, int y) {day = D; month = m; Year = y; }//Omit get Set public void display () {System.out.println (day + "-" + month + "-" + year); }}public class test{public static void Main (String args[]) {test test = new test (); int date = 9; BirthDate d1= New BirthDate (7,7,1970); BirthDate d2= New BirthDate (1,1,2000); Test.change1 (date); Test.change2 (D1); Test.change3 (D2); System.out.println ("date=" + date); D1.display (); D2.display (); } public void Change1 (int i) {i = 1234; } public void Change2 (BirthDate b) {b = new BirthDate (22,2,2004); } public void Change3 (BirthDate b) {b.setday (22); }}
The results are as follows:
Date=9
7-7-1970
22-1-2000
What I do not understand is change2 this method, it unexpectedly did not change the value of D1!
In fact, we understand that when the change2 is running, there is another area in the stack memory, and the local variable b is stored. When Change2 is running, b first points to the location of the argument D1. It was 7-7-1970 and then new birthday, assuming that it was in the heap memory address of 5421 then B's value changed to 5421 change2 This method ends, b This memory also disappears. D1 Nature will not change anything.
Look at Change3 again.
When you run this method, the first point that B points to is the location of the argument D2. We modify the memory data directly through B, so the value of the D2 variable naturally changes.
Parameter passing and memory allocation problems in Java