java dynamic memory allocation?

33,488

Solution 1

All Java objects are dynamically allocated. You're always passing around references to them. This is how the language is designed. When you do:

ClassA obj = new ClassA();

Then the object is allocated on the heap and a reference to it is stored on the stack (assuming that's inside a method, of course). What this means is that you can always pass objects about without worrying about where they are stored.

Solution 2

It's dynamic since you don't know when it needs allocating - you allocate upon demand.

Note also that you know how much memory that object requires, but not how much that object's members require. This may only be determinable at run time (e.g. an array of variable size).

Share:
33,488
JavaUser
Author by

JavaUser

Updated on September 12, 2020

Comments

  • JavaUser
    JavaUser over 3 years

    Why is an object initialization using the new keyword called dynamic memory allocation, since compile time itself we need to know the memory needed for that object.

    Also please explain what happens when you do ClassA object = new ClassA(); in heap and stack .