Executing a java program without main()

This question is asked by many interviewers during the technical interview. So, the question is self-explanatory. We have to execute a java program without using

We do this by using a static block or static initializer block. A static block is always executed before main(). Also a point to note that a static block does not have a return type and it does not accept any arguments.
Another important point to be noted is that one should never forget to use

in the static block to prevent no method found exception.

Output:
java program without main

The following two tabs change content below.
  • sivaswami

    >java StaticDemo
    Error: Main method not found in class StaticDemo, please define the main method as:
    public static void main(String[] args)

  • michael3ov

    Yes it will compile but so what. It throws a runtime error. You have to define main.

    • Vlad

      It is not an error, but a warning which can be ignored.

      • Priyanka

        You get an error, if you use JDK 1.7. It can run successfully on JDK 1.6 or lower version..