views:

187

answers:

2

Why is an object initialization using the "new" keyword called dynamic memory allocation, since compile time itself we know the memory needed for that object. Also please explain what happens when you do ClassA object = new ClassA(); in heap and stack .

+3  A: 

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.

Donal Fellows
Why the object is stored in Heap and the reference is stored in Stack ?
JavaUser
The stack holds the local variables of the method call. Here, I assumed that the `obj` variable was in a method call, so obviously the reference to the object is on the stack. The object itself is on the heap, as with every other Java object in the whole program. Even the classes are on the heap (though a JIT compiler might do some extra tricks behind the scenes).
Donal Fellows
+3  A: 

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

Brian Agnew