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?
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.
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.
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).
In Java everything allocated with new, is allocated from the heap. Local variables of primitive types are allocated from the stack.
精彩评论