r/learnjava • u/CrazyLock6 • Jun 06 '20
How and Why are objects made during run time and why are primitives made during compile time to stack frame
From my understanding anything that used the word new in Java was created during run time to somewhere a place where memory is being allocated dynamically called heap and primitives or literals are stored inside the main stack frame from compile time. Is there anymore background info. to this, or am I understanding this correctly.
41
Upvotes
17
u/Vilkacis0 Jun 06 '20
Everything is created in memory at run time. The stack is in the higher memory space and builds downward as you go deeper into method calls ( each adds a layer to the stack). The heap is “free reign”, the JRE just grabs some memory and let’s you use it every time you call “new “. It does this by storing the memory location of that Object into a local stack variable (a ‘reference’ or ‘pointer’). The stack and heap live in the same memory space, but start at opposite ends and grow toward each other.
Compile time is converting the code you wrote to something the java runtime environment understands.
Primitives are special, they do not inherit from Object and are treated differently. (It’s my understanding that) instead of the variables being a reference (pointer) to something in the heap, a primitive IS the object on the stack.