javamethodsconstructorstackstate-saving

Does constructor call also go on the stack?


I understand that in Java all method calls go on a stack. Take the following class for instance:

Class Demo
{
   // Some instance variables
   public Demo()
   {
      initialize();
   }

   public void initialize()
   {
      // Start initialization
      ....

      // Call another method to perform some complex calculation
      int resultVal = helperMethod();

      // Perform the remaining initialization work

   }


   public int helperMethod()
   {
      // Perform some complex calculation 
      ....

      return result;
   }

}

First initialize() (with its state) is pushed onto the stack and then when it calls helperMethod() ,state for helperMethod() is pushed onto the stack too.

But what i want to understand is , is state for Demo() first pushed onto the stack (before even initialize() is pushed) , despite it being a constructor and not a method ?

Are there notable differences between saving constructor state and method state ?


Solution

  • When it really comes down to it a constructor is just like any other method. It takes parameters of whatever types and returns an object of its own type. It's put on the call stack like anything else, and shows as Demo.<init>()

    An exception in your example call stack-trace would look like

    Exception in thread "main" java.lang.NullPointerException
        at Demo.helperMethod(Demo.java:30)
        at Demo.initialize(Demo.java:16)
        at Demo.<init>(Demo.java:7)           <---------
        at Demo.main(Demo.java:36)