Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java dynamic memory allocation?

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 .

like image 391
JavaUser Avatar asked Mar 28 '10 11:03

JavaUser


People also ask

What is dynamic memory allocation in Java with example?

Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.

Does Java support static memory allocation?

Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap. Access to this memory is in Last-In-First-Out (LIFO) order.

What is static and dynamic memory allocation in Java?

When the allocation of memory performs at the compile time, then it is known as static memory. When the memory allocation is done at the execution or run time, then it is called dynamic memory allocation.

How do I fix Java heap space error?

OutOfMemoryError: Java heap space. 1) An easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError.


1 Answers

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.

like image 71
Donal Fellows Avatar answered Oct 26 '22 19:10

Donal Fellows