when we create an object ,do creation of object and the execution of constructor happens at the same time?

When we create an object, do creation of object and the execution of constructor happens at the same time or first object is created then constructor execution take place?

Its written in the Herbert Schildt: "Once defined ,the constructor is automatically called immediately after the object is created ,before the new operator completes". My queue is that if new operator has not finished with it's memory allocation then how can be constructor be called before new gets completed as it's written constructor is called only after object is created.

Jon Skeet
people
quotationmark

Section 12.5 of the JLS gives the details. The bare bones of it is:

  • Memory space is allocated (with all fields having the default value for the relevant type, e.g. null or 0)
  • The specified class's constructor is called, which will immediately chain to either another constructor in the same class or a superconstructor
  • Eventually the chain reaches java.lang.Object
  • In each constructor chain coming back down, instance variables are initialized based on their field initializers, if any (and only if we didn't chain to another constructor in the same class), then the constructor body code executed. That then returns to the calling constructor, etc.

The JLS goes into more detail, of course, including cases where there isn't enough memory or a constructor body throws an exception.

The timing of each bit of the constructor is important though:

  • Chain to this/super constructor
  • (Implicit) Assign initial values to fields if the chain was to a superclass constructor
  • Constructor body

It's important to understand that if a superconstructor invokes an overridden method which reveals the value of a field, it will not have gone through the field initializer yet. So you can see the default value of the field rather than the value you'd expect to from the initializer. For example:

class Bar extends Foo {
    private String name = "fred";

    @Override public String toString() {
        return name;
    }
}

If the Foo constructor calls toString(), that will null rather than "fred".

(If name is final, then it's treated as a constant in toString() and other things happen, but that's a different matter.)

people

See more on this question at Stackoverflow