java dynamic memory allocation?

0 votes
asked Mar 28, 2010 by javauser

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 .

3 Answers

0 votes
answered Mar 28, 2010 by donal-fellows

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.

0 votes
answered Mar 28, 2010 by brian-agnew

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).

0 votes
answered Mar 18, 2015 by asad-mukhtar

If you have a class of JMath and you want to get all its objects on runtime(Dynamically allocation) then you just wrote

ArrayList<JMath> J = new ArrayList<JMath> ();
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...