• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Program without main method

 
Sujoy Mukherjee
Ranch Hand
Posts: 51
Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Srikkanth Mohanasundaram
Ranch Hand
Posts: 243
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static block runs when the class loads,that why you get to see the output.

Regards,
Srikkanth
 
Sujoy Mukherjee
Ranch Hand
Posts: 51
Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot folks, both marc and Srikkanth....that helped a lot.
 
Sujoy Mukherjee
Ranch Hand
Posts: 51
Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops sorry, how could I forget Ulf.....he was the first one to post a reply.......Thankz again Ulf.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic