2

Example Classes

************ Example.java ************

public class Example {

    public static void main(String[] args) {
         Test test = new Test();
         test.hello();
    }
}

**************   Test.java ************

public class Tets {    
    public void hello() {
         System.out.println("Hi");
    }
}

My Understanding: In Example.Main method, test reference will get stored in Java stack memory and Since new Test() Object has no state so There won't be any Heap memory allocation.

Doubt: Usually We say that Objects get stored in Heap memory but here we don't have any state fields for Test Object, Then will there be any memory allocation in Heap Memory?

1 Answers1

3

There will be an instance created in the heap, even if there are no fields; additionally there will be 2 headers for this instance created : mark and class. You are calling hello on an instance after all and the java language specification explicitly says that Object instances are created in the heap.

When the code runs enough times, JIT will kick in - at some point, it might prove that a certain instance might not be needed and might elide that allocation away. Or, if the instance is purely local and does not escape an optimization called scalar replacement might happen, when an instance could be dissolved into fields, and not allocated in the heap.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Eugene
  • 117,005
  • 15
  • 201
  • 306