Skip to content

Main Method

This content is for Java. Switch to the latest version for up-to-date documentation.

The main method is the entry point for every Java application - it’s where program execution begins.

public class MyClass {
public static void main(String[] args) {
// Program execution starts here
System.out.println("Hello, World!");
}
}
  • public: Access modifier making the method accessible from anywhere
  • static: Makes the method accessible without creating an instance of the class
  • void: Return type indicating the method doesn’t return any value
  • main: Method name (must be exactly “main”)
  • String[] args: Command-line arguments passed to the program

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: first
Argument 1: second
Argument 2: third
  • 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
  • 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
Built with passion by Ngineer Lab