I am currently learning the memory concepts of java, the stack and the heap, I know that local variables and method calls lived in a place called stack. and objects lived inside a heap. but what if that local variable holds an object? or has an object reference?
public void Something(){
Duck d = new Duck(24);
}
Does it still live inside a stack? and where do instance variables live? please keep it simple as possible. thank you.
Local variable d
(allocated on stack) contains a reference to an object of class Duck
. In general objects are allocated on the heap.
Java 6e14 added support for something called 'escape analysis'. When you enable it with -XX:+DoEscapeAnalysis
switch, then if JVM determines that an object is created in a method, used only in that method and there is no way for reference to the object to 'escape' that method - that is, we can be sure that the object is not referenced after method completes - JVM can allocate it on stack (treating all its fields as if they were local variables). This would probably happen in your example.
Fields are allocated with the rest of the object, so on the heap or on the stack, depending of escape analysis results.
Object reference variables work. just like primitive variables-if the reference is declared as a local variable, it goes on the stack.else if refrence is instance variable it will go into the heap within an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With