How to Run Java Program Without Main Function??

Hi Animesh ,
I was asked the question in my semester -"How to Run Java Program Without Main Function??" In a leading book it is said yes and they gave explanation...I did not understand the concept.
Can you please tell me why?

Hi Sunita,
Thank you very much for writing to me .Yes Surely we can run a Java Program without main method.
In Java, a static initializer gets executed as soon as the class is
loaded, even before the main method is called!!!.

So if we create a static block  and give some command inside it. It will execute.The JVM finds and loads the class into memory when you run this code,the static initializer is executed during the loading and
initialization of the class.
But my suggestion is do not use this feature while developing your application. And even if you use this feature please make sure to incorporate
System.exit(0); After your code
System.exit(0) is called at the end of the static block to terminates the program. If not, then the JVM would have next used reflection on that class to find the main() method. If it does not find the main method, it throws an exception. if we don't write main() in the program then the compiler doesn't know
where to start the program..

public class WithoutMain {
static {
System.out.println( "Hello World" );

I have taken help from
How to Run Java Program Without Main Function?? How to Run Java Program Without Main Function?? Reviewed by Animesh Chatterjee on June 18, 2012 Rating: 5

No comments:

Powered by Blogger.