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?
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.
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