简体   繁体   中英

Where is memory allocated for instances and the values of variables in Java?

When we instantiate a class where is that stored? and where does the values inside the object are stored.

example:

MyDemoClass obj1 = new MyDemoClass();

where is obj1 stored??

and if I do

obj1.x = 10;

Where is the x stored?

where is this 10 stored?

And if we make variable x static

class MyDemoClass {
    static int x;
    MyDemoClass() {
        x = 10;
    }
}

Now where is x stored and where is value 10 stored?

Can someone explain it in simple words?

Thank You for taking your time for this newbie doubt!

MyDemoClass obj1 = new MyDemoClass();

where is obj1 stored??

obj1 is just a label/pointer. In memory it will be assigned to the stack. The object that obj1 points to will be on the heap (all objects in Java exist on the heap)

and if I do

obj1.x = 10;

Where is the x stored?

x is stored on the heap with the object

And if we make variable x static where is this 10 stored?

x is then stored on the heap, associated with the MyDemoClass Class object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM