Makakmayum@makakmayum_sid
#JavaInterviewQuestion
Does creation of object with new always happen on the heap?
Everyone thinks so.
But it might not be, if JVM thinks that it doesn't need to.
Let's see an example:
class Point { int x, y; }
int sum() {
Point p = new Point();
p.x = 10; p.y = 20;
return p.x + p.y;
}
Inside sum method, it seems a Point object is created.
Here comes JIT compiler, it analyzes the code:
•Does p escape this method?
•Is it returned, stored, or passed somewhere else?
If the answer is no, the JVM cancels the heap allocation.
This is called Escape Analysis.
It goes further: instead of creating a Point, the JVM replaces it with its fields (int x, int y).
This is Scalar Replacement.
So the new Point() you see in code never actually exists at runtime.
The JVM just works with two integers directly.
Why it matters:
•No heap allocation → no GC pressure
•Faster execution → stack-allocated scalars
•Short-lived objects are cheap → the JVM often optimizes them away
That’s why the old advice “object creation is expensive” is mostly a myth in modern Java.
3419980



