Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Where do Local variables,Object references,instance variables

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.

like image 220
KyelJmD Avatar asked Dec 21 '11 10:12

KyelJmD


2 Answers

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.

like image 64
socha23 Avatar answered Oct 20 '22 13:10

socha23


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.

like image 44
yasir Avatar answered Oct 20 '22 14:10

yasir