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

Time:09-14

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!

CodePudding user response:

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
  • Related