Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

main()

 
ashok ks
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the use of using main() in the java class ?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a wee bit of magic involved. Really it's just a convention established by the inventors of the language. When you start a Java program at the commandline "java ClassName" the Java runtime loads the class and calls the main() method. The runtime also puts any parameters you entered on the commandline into the String[] parameter for main.
So when you see a main() method, it means you can start the class from the command line. Sometimes that means it is "the program of interest" or the thing people actually want to start up from the command line. Sometimes the main method is just for testing. Some classes that you would never run as a program from the command line have test code or examples of how to call methods in the main.
If you're using an IDE like Eclipse you usually have a "run" button of some kind instead of using the command line launch.
hope that helped!
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In short, main() is just the place where the program starts. The only reason it's special is because the people that made Java said so.
 
Sadanand Murthy
Ranch Hand
Posts: 382
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by ashok ks:
What is the use of using main() in the java class ?

Since others have already explained why main() is there, I'll just mention that it is required ONLY if you java class is the entry point to an application. If it is not an application entry point then it will not have main().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic