Parameter passing and memory allocation problems in Java

Source: Internet
Author: User

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

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.