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
|
1 |
public static void main(String args[]) |
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
|
1 |
System.exit(0); |
in the static block to prevent no method found exception.
|
1 2 3 4 5 6 7 |
public class StaticDemo { static{ System.out.println("Works without main()."); System.exit(0); } } |
Output:

>java StaticDemo
Error: Main method not found in class StaticDemo, please define the main method as:
public static void main(String[] args)
Yes it will compile but so what. It throws a runtime error. You have to define main.
It is not an error, but a warning which can be ignored.
You get an error, if you use JDK 1.7. It can run successfully on JDK 1.6 or lower version..