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