In java objects, Can Can be instantiated with both static memory allocation and dynamic memory allocation?

In java objects Can I create objects with both static memory allocation and dynamic memory allocation?

+2


source to share


4 answers


If by static memory you mean on the stack, no, all objects are allocated on the heap. Only primitives are allocated on the stack.

Edit: I'm still not sure if you understand heap and stack respectively by dynamic and static values, but this is usually a question that people with a C / C ++ foundation have, since those languages ​​give the developer control over what.

In Java, when you do typical:

 Object o = new Object();

      



This will allocate memory on the heap. If inside a method you do:

 int i = 1;

      

This int is then allocated on the stack (if this field is in a class, then it will be allocated on the heap).

+2


source


All memory of the instance (by calling new) is allocated on the heap, all parameters are allocated on the stack. But java (not primitive) parameters are passed by reference (excluding primitives).



0


source


"Static" does not mean "on the stack".

Objects allocated during the initialization of static class variables or static code blocks are statically allocated in the sense that allocation occurs at class load time (which can be done to statically start immediately after starting the program).

In theory, you could write a java program using only such allocations and it would be statically allocated , the same as C which was never called malloc, just had fixed buffers for what it wanted to do.

If such a program runs successfully, it proves that there is enough memory for everything it can do, and therefore it will never get an out-of-memory error, fragmentation issue, or GC pause.

It will simply, if written correctly, return a lot of error messages that say "I can't do this."

0


source


Answers that assert that non-primitives are always heap allocated are dead wrong.

JVMs can analyze to determine if objects will always be limited to a single thread and that the lifetime of an object is limited to the lifetime of a specific stack frame. If it can determine that an object can be allocated on the stack, the JVM can allocate it there.

See this article for details .

-1


source







All Articles