Main Method
The main method is the entry point for every Java application - it’s where program execution begins.
Basic Structure
Section titled “Basic Structure”public class MyClass { public static void main(String[] args) { // Program execution starts here System.out.println("Hello, World!"); }}Main Method Components
Section titled “Main Method Components”public: Access modifier making the method accessible from anywherestatic: Makes the method accessible without creating an instance of the classvoid: Return type indicating the method doesn’t return any valuemain: Method name (must be exactly “main”)String[] args: Command-line arguments passed to the program
Command-Line Arguments
Section titled “Command-Line Arguments”The String[] args parameter allows passing information to your program when it starts:
public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("Argument " + i + ": " + args[i]); }}When executed with: java MyClass first second third
Output:
Argument 0: firstArgument 1: secondArgument 2: thirdMultiple Main Methods
Section titled “Multiple Main Methods”- A Java project can have multiple classes with main methods
- The JVM executes the main method in the class specified at runtime
- This allows different entry points for different purposes
Best Practices
Section titled “Best Practices”- Keep the main method simple and focused on program initialization
- Consider extracting logic to separate methods and classes
- Use command-line arguments for configuration when appropriate