aspose file tools*
The moose likes Beginning Java and the fly likes Program without main method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Program without main method" Watch "Program without main method" New topic
Author

Program without main method

Sujoy Mukherjee
Ranch Hand

Joined: Dec 31, 2005
Posts: 51

hello friends,
generally we know that the execution of any java program always starts from main method and without main, no program will compile.
But it does. I found the following code from net....it is without main method, surprisingly it compiles and runs smoothly.


My Question is - How is it possible?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42612
    
  65
without main, no program will compile.

The vast majority of java classes do not have main method. The compiler doesn't care whether or not a class has a main method.

The program quits before the class is initialized, so the JVM never gets a chance to determine that the main method is missing (which it would, and exit the program with an error message, if the call to exit were removed). I wouldn't call that "running smoothly".


Ping & DNS - my free Android networking tools app
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

An old Java parlor trick: Execute static code when the class is loaded, then get out of Dodge using System.exit(0) before an Exception is thrown.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Srikkanth Mohanasundaram
Ranch Hand

Joined: Feb 07, 2007
Posts: 185
The static block runs when the class loads,that why you get to see the output.

Regards,
Srikkanth
Sujoy Mukherjee
Ranch Hand

Joined: Dec 31, 2005
Posts: 51

Thanks a lot folks, both marc and Srikkanth....that helped a lot.
Sujoy Mukherjee
Ranch Hand

Joined: Dec 31, 2005
Posts: 51

Oops sorry, how could I forget Ulf.....he was the first one to post a reply.......Thankz again Ulf.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Program without main method