beginnerFree

The main() Method

Where every Java program begins

The main() Method

The JVM starts your program by calling public static void main(String[] args). Command-line arguments arrive in args.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:16

The Big Picture

main is the single entry point the JVM calls to start your program. The classic signature must match this form or the JVM won't find it.

  • public - reachable from outside the class (the JVM calls it)
  • static - runs without creating an object first
  • void returns nothing · String[] args carries command-line input

How It Works

The java launcher loads your class, then the JVM invokes main on the "main" thread. Tokens typed after the class name become args.

  • java Greet Alice Bob → args = {"Alice", "Bob"}
  • Every element is a String - parse numbers with Integer.parseInt
  • The shell splits on spaces; quote to keep a token together

In the Java Landscape

The classic form is stable, but a few variants are worth knowing.

  • String... args (varargs) is an equally valid signature
  • System.exit(int) sets the process exit code (0 = success)
  • Java 25 finalizes a simpler instance main + compact source files

(preview in Java 21-24) - the classic form still works everywhere

Pitfalls and Best Practices

  • A signature typo → "Main method not found" - the JVM won't start
  • args is never null but can be empty - guard args.length
  • Reading args[0] with no input → ArrayIndexOutOfBoundsException
  • Keep main thin - delegate real logic to other methods/classes
#java#fundamentals#entry-point