5

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

5 Comments

allocated inside the object they are in? or as in solo in the heap?
what if the the object is created as an instance variable would it still fall under the Escape analysis?
the layout of an object in memory is like this: 8 bytes header, and then the attributes. If the instance variable is an Object, not a primitive, then only the pointer is stored in continouous memory block, and the object can be allocated elsewhere.
According to release notes (oracle.com/technetwork/java/javase/6u14-137039.html) instance variables of stack-allocated objects are treated just as local variables, so I guess they would be alo allocated on stack.
Okay thank you. now there's a reason for me to upgrade my java virtual machine. I haven't updated it since I found that there's no changes, but guess I was wrong. Thank you everyone.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.