tags:

views:

119

answers:

4

This is Just for my understanding.Objects which are class members go into heap while local variables and value types got o stack.Is there a usecase and possibilty to push the object to Stack or heap forcibly?

+5  A: 

No, Java doesn't allow direct access to memory. I don't think that there is a use case for this. This isn't possible even in C++, where certain rules apply regarding where objects are saved. You will need to implement your own memory management routines to do so and that will be cumbersome and platform dependent.

kgiannakakis
There isn't a 'use case' for this because it isn't required. See my reply below. The remark about C++ is also incorrect - you can specifically allocate an object on the stack, and I have written whole applications that did nothing else.
EJP
+2  A: 

Yes and no - i think there is a conceptual misinterpretation here.

If by forcing an object on the heap, you mean you wish it to remain "alive" even after a call to the method which created it, then yes. All you need is to retain a reference to it.

If by forcing an object on the heap, you mean you would like to specify where that object's memory is allocated from, then no (not without some jni funky stuff).

Chii
+2  A: 

In Java everything allocated with new, is allocated from the heap. Local variables of primitive types are allocated from the stack.

Lauri
These were the old rules. Escape analysis changes this. "Objects" may be on the stack.
Thomas Jung
Still, you should not notice the difference except in performance.
Tobias Langner
@Thomas Thanks! It is nice to see that you can learn something new every day... It seems that escape analysis is still in experimental state and you have to enable it explicitly when launching vm, am I right?
Lauri
Yes, until JDK 7.
Thomas Jung
+2  A: 

Objects which are class members go into heap.

No. Objects go into the heap.

... while local variables and value types [go to] stack.

No. All local variables are allocated on the stack. If they are references to objects, the objects concerned are in the heap if they exist.

Is there a usecase and possibilty to push the object to Stack or heap forcibly?

No. You don't need one. All objects are allocated on the heap.

EJP