6

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 3

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why the object is stored in Heap and the reference is stored in Stack ?
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).
6

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

Comments

0

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> ();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.