Java parameter passing and Memory Allocation Problems

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.