Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime vs compile time memory allocation in java

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

For example:

class Test{
  int a;
  public Test(){
    a=10;
  }
};

// somewhere else
Test t = new Test();

Is a allocated at run time or at compile time? If at compile time, how is it possible as java runs on a VM which directly takes compiled .class files?

Also:

  • when is a assigned the value 10?

  • how does it work for reference variable t?

Thanks.

like image 381
user1649415 Avatar asked Dec 05 '22 14:12

user1649415


2 Answers

Compile time no memory allocation happens. Only at load and runtime.

Compile time generates .class files that's it.

Remember you need to have a main class to run the program. When you run your program using Java with classpath to .class file, there will be steps like loading & linking etc.,

Classloaders loads the files to permgen.

When main method invoked, there will be stack created and local variables will be placed there

When runtime encounters new it creates object on heap and allocates required memory there like memory required for Test.

like image 103
kosa Avatar answered Dec 13 '22 08:12

kosa


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.

like image 45
Peter Lawrey Avatar answered Dec 13 '22 08:12

Peter Lawrey