Pawan
Pawan

Reputation: 32321

Java heap and stack memory allocation

class Person{
          private String name;
          public Person(){
          }

          public Person(String name){
              this.name=name;
          }

          public static void main(String[] arg)
          {
                Person per= new Person("Andy");
          }
    }

per is a local variable, where will it be stored, on the heap or the stack?

Upvotes: 6

Views: 4545

Answers (2)

someguy
someguy

Reputation: 7334

Objects are always stored in the heap. However, the reference to per will be stored in the local variable array, which is stored in the frame created for main(String[]), which is stored in the stack.

For more information, see: The Structure of the Java Virtual Machine.

Edit: I've learnt that JVMs are actually able to allocate objects on the stack by performing escape analysis. Better yet, a technique called scalar replacement can be applied, where the object allocation is omitted, and the object's fields are treated as local variables. It is possible for the variables to be allocated on machine registers.

Escape analysis by stack allocation has been implemented by HotSpot VMs since Java 6u14. It has been enabled by default since Java 6u23. For an object to be allocated on the stack, it must not escape the executing thread, the method body or be passed as an argument to another method.

Upvotes: 30

highlycaffeinated
highlycaffeinated

Reputation: 19867

On the heap. Any time you use new to create an object, it is allocated on the heap.

Upvotes: 0

Related Questions