Runtime vs compile time memory allocation in java

前端 未结 4 2078
野的像风
野的像风 2021-01-03 06:11

I am confused regarding whether memory allocation in java occurs at run time or compile time.

For example:

class Test{
  int a;
  public Test(){
             


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 06:36

    Local variables and method parameters such as primitives or reference, are notionally allocated a place on the stack at compile time.

    At runtime, this isn't guaranteed to to reflect how it is laid out in memory.

    Allocation of objects on the heap only occurs at runtime.

    how is it possible as java runs on VM which directly takes compile .class file.

    Only the VM knows how the code will be compiled so it not possible to do memory allocation at compile time.

    when is a assigned value 10

    At the line where the assignment occurs. Given its not used, the JIT can discard it so it might no happen at all.

    Also the same question stands for reference variable t.

    t is assigned where the = is after the object is constructed.

提交回复
热议问题