is the member variable initialized in the Java class stored in heap memory or in stack memory?

Source: Internet
Author: User

The answer is heap memory.


Before clearly reading the Java class initialization process,

But suddenly see such a topic, still ignorant.

After Baidu, those post reply each have each say,

The head can see the fortress live, or read the book to prove it.


The 128th page of Li Gang's crazy Java begins with a class that starts with initialization,

The detailed process of what happens in memory is briefly recorded here.

Class person{String name; static int eyenum;}


Above this person class, there is a member variable name and a static member variable Eyenum,

When the following statement is executed:

person P1 = new person (); person P2 = new Person ();p 1.name = "A";p 2.name = "B" p1.eyenum = 2;p2.eyenum = 3;


    1. person P1 = new person (); The first time you use the person class, the system allocates space for the person class in heap memory, which also includes the static member variable Eyenum (the initial value is 0).

    2. Then, in heap memory new a person object, where name is null, and then point P1 to the object.

    3. Then new P2, because the class has been initialized, just repeat the 2nd step.

    4. P1.name = "a"; Let the name of the P1 object in the heap memory point to a "a" string.

    5. P1.eyenem = 2; The Eyenum property of the person class is assigned a value of 2 by modifying the class property of person (because it is a static member variable) through the Person object.





Person class









Eyenum→2






P1
------
-- ---------------- ---





Second Person object


First Person Object



P2
------

name→
B
name→
A











Stack memory


Heap

Within

Save




It's hard to see, but that's probably the way it is.





is the member variable initialized in the Java class stored in heap memory or in stack memory?

Related Article

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.