Java parameter passing and Memory Allocation Problems
This article can be used as a learning note for the Beijing shangxue java course.
See the following code.
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 (1970, 2000); BirthDate d2 = new BirthDate (,); 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 result is as follows:
Date = 9
7-7-1970
22-1-2000
What I don't understand is the change2 method. It didn't actually change the d1 value!
In fact, when change2 is running, there is another area in the stack memory to store the local variable B. When change2 is running, B first points to the position of the real parameter d1. That is, a new birthday is created after 7-7-5421. Assuming that the heap memory address is 5421, then the value of B is changed to and the change2 method ends, B memory disappears. D1 naturally remains unchanged.
Let's look at change3.
When running this method, B first points to the location of the real parameter d2. We directly modified the data in that memory through B, so the value of the variable d2 naturally changed.