Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Program without main method

 
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?
 
Rancher
Posts: 43016
76
  • 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".
 
Sheriff
Posts: 11343
Mac Safari Java
  • 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.
 
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.
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic