In java Can objects be created with both static memory allocation and dynamic memory allocation?
views:
661answers:
4In java Can objects be created with both static memory allocation and dynamic memory allocation?
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 by dynamic and static you mean heap and stack, respectively, but that is usually where the question comes from for people with a C/C++ background, because those languages give the developer control over that.
In Java, when you do a typical:
Object o = new Object();
That will allocate memory on the heap. If inside a method you do:
int i = 1;
Then that int is allocated on the stack (if it is a field in a class, then it will be allocated on the heap).
All instance memory (by calling new) is allocated on the heap, all parameters are allocated on the stack. But java (non primitive) paramters are all passed by reference (excepty primitives).
The answers claiming that non-primitives are always allocated on the heap are dead wrong.
JVMs can do escape analysis to determine whether objects will always be confined to a single thread and that the object's lifetime is bounded by the lifetime of a given stack frame. If it can determine that an object can be allocated on the stack, a JVM may allocate it there.
See this article for details.
'Static' doesn't mean 'on the stack'.
Objects allocated in the initialisation of class-static variables, or in static code blocks, are statically allocated, in the sense that allocation is done at class-load time (which can be made to happen statically immediately after program startup).
You could, in theory, write a java program using only such allocations, and it would be statically allocated, the same as a C program that never called malloc, just had fixed buffers for the stuff it wanted to do.
If such a program successfully starts up, that proves there is enough memory available for everything it can do, and so it will never get an out of memory error, fragmentation problem, or GC pause.
It will just, if correctly written, return a lot of error messages saying 'I can't do that'.