[Solved] In java constructor and main which one will execute first?


The main method will always be excecuted first, because it is a special static method that will be called from Java itself to start an application.

For more about the main method please read Java main() Method Explained for example.

Constructors will be created on object creation – in your case no object creation happens – so the constructor will never be executed.

You could modify your example to also execute the constructor:

public class ConstructorExp {
  public ConstructorExp() {
    System.out.println("Ctt");
  }

  public static void main(String[] args) {
    System.out.println("Inside Main Methos");
    ConstructorExp example = new ConstructorExp();
    System.out.println("Main");
  }
}

Be carefully, because the example object is never used the constructor call might be eliminated by some kind of optimization depending on the compiler you are using.

solved In java constructor and main which one will execute first?