How to Run Java Program Without Main Function??

    0
    40
    Spread the love
    • 2
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      2
      Shares

    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

    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 2
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      2
      Shares

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here