• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

can there be class without main() method

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,

i want to know if we can have class without main() method, if yes then how come and what will be the output in that case.

i have one more query, why we cannot have prvate static void main(String[] args){}
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all, it is perfectly legal to have a class with no main method. The purpose of the main method is to indicate a "point of entry" into the code. Without a main method, where would you start executing your code?

If you don't declare a main method, you simply can't execute that class from the command line. However, there's nothing stopping other classes from using it. Here's an example:



As far as having a private main method goes, you can do that, too. The key here is that, when the JVM tries to begin execution of a class, it will look for a method with the signature "public static void main(String[] args)". If your main method is declared as private, the JVM will not be able to execute it.

*Caveat: There have been known issues in the past in which compilers would execute a non-public main method. I would interpret this as a "bug" as the JLS clearly states that the entry for execution must have the signature "public static void main(String[] args)". If you get this question on the exam, go with what the JLS states.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic