Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » » » 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?
Regards,
Sunita

Hi Sunita,
Thank you very much for writing to me .Yes Surely we can run a Java Program without main method.
How::
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" );
System.exit(0);
}
}

I have taken help from http://www.xyzws.com/Javafaq/can-a-java-application-run-without-a-main-method/63

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply