Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 201 ยท Methods

The main Method and Command-Line Arguments

Understand every word of public static void main(String[] args), Java 25 instance main methods, reading and parsing command-line arguments, and exit codes with System.exit.

Every Java program starts somewhere. When you run java Main, the JVM loads the class, looks for a method called main, and calls it. Everything your program does happens inside that call or in methods it calls. When main returns (and no other non-daemon threads are still running), the program ends.

For decades that method had to be written exactly as public static void main(String[] args), a line beginners copy for months before they understand it. Java 25 relaxed the rules, which is why short examples on this site start with just void main(). This lesson explains both forms word by word, shows how the JVM chooses which main to call, and teaches you to read command-line arguments and report success or failure with exit codes.

Every word of public static void main(String[] args)

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello from the classic main");
    }
}
Part Meaning
public Visible from anywhere, so the launcher can call it from outside the class.
static Belongs to the class, not to an object. The JVM can call it without creating a Main object first. See Static vs Instance Methods.
void Returns nothing. A program reports its result through output and its exit code, not a return value.
main The name the launcher looks for. It's not a keyword; it's just a method name with a special job.
String[] args An array of the words typed after the class name on the command line. The name args is only a convention.

A few variations are equally valid for the classic form:

Java
public static void main(String... args)        // varargs: the same as String[]
public static void main(final String[] args)   // final parameter
static public void main(String[] arguments)    // modifier order and name don't matter
public static void main(String args[])         // legal, but old C-style array syntax: avoid

Things that are not an entry point: a different return type (int main), a different parameter type (main(int[] x) or main(List<String> args)), or a misspelled name (Main). Those compile fine as ordinary methods; the launcher then complains that it can't find a main method.

Java 25: compact files and instance main methods

Java 25 finalized two features that make small programs much shorter (JEP 512):

  • Compact source files: a file can contain methods and fields without any class declaration around them. The compiler wraps them in an unnamed class for you, and all of java.base (List, Map, Arrays, ...) is imported automatically.
  • Instance main methods: main no longer has to be public, static, or take String[] args. If it's an instance method, the launcher creates an object with the no-argument constructor and calls main on it.

So this is a complete Java 25 program:

Java A compact source file with an instance main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because main here is an instance method, it can use the fields greeting and launches directly, without the word static anywhere. The implicit class takes its name from the file name; our editor saves your code as Main.java, so it prints Main. You can't refer to that name in your own code, though, which is why compact files suit single-file programs.

Instance main methods also work in ordinary named classes:

Java An instance main in a named class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How the launcher chooses a main method

When a class has more than one candidate, the launcher picks in this order:

  1. A main with a String[] parameter (static or instance), if there is one.
  2. Otherwise, a main with no parameters (static or instance).

The method must not be private. If the chosen main is an instance method, the class needs a non-private constructor with no parameters, and the launcher calls it first. In practice: library code, frameworks and most existing projects still use the classic public static void main(String[] args), and you'll read it every day. Compact files and instance main are perfect for scripts, experiments and learning. Both are first-class Java.

Command-line arguments

When you start a program from a terminal, everything after the class or file name is split into words and handed to main as args:

Terminal
java Main.java report.csv --verbose "New York"

Here args is {"report.csv", "--verbose", "New York"}:

  • The shell splits on spaces; quotes keep "New York" as one argument, and the quotes themselves are removed.
  • args[0] is the first argument, not the program name (unlike C and Python's sys.argv).
  • With no arguments, args is an empty array, never null. args.length is 0.
  • Every argument is a String, even 42. Converting is your job.

Our editor's Run button starts the program with no arguments, so args.length is always 0 here. That's actually a good habit-builder: real programs must handle missing arguments gracefully. To see different argument lists, the examples below move the real work into a method and call it with arrays you build yourself, which is also how you'd unit test it.

Java Reading args, with simulated command lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Always check args.length before reading args[i]. Reading args[0] when no arguments were given throws ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0, one of the most common crashes in beginner programs.

Parsing options and flags

Real tools accept options like --verbose, --size=10 or -n 5, mixed with plain values. A small loop over args handles most needs:

Java A tiny option parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few habits make argument handling robust:

  • Give defaults for optional settings, so the program runs with no arguments at all.
  • Validate early and print a clear usage line: Usage: tool [--verbose] [--size=N] file....
  • Convert carefully. Integer.parseInt throws NumberFormatException on bad input (see Type Casting and Conversion); catch it and explain the problem in plain words.
  • Bundle the result in a record, as above, instead of passing many loose variables around.

For big command-line tools, libraries such as picocli generate parsing, help text and validation from annotations. For small programs, a loop like this is all you need.

Exit codes and System.exit

When a program ends, it hands the operating system a number, the exit code (or exit status). By convention 0 means success and anything else means failure; scripts and build tools check it to decide whether to continue.

How the program ends Exit code
main returns normally 0
An uncaught exception escapes main 1 (and the stack trace is printed)
System.exit(n) is called n

System.exit(n) stops the whole JVM immediately, from anywhere in the program. Code after it never runs, and neither do pending finally blocks in the current thread. The run below exits with code 3 on purpose; our output panel reports it as "The program exited with code 3.":

Java Exiting with a failure code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the error message goes to System.err, the standard error stream. Keeping error messages out of standard output means a user can redirect the normal output to a file and still see errors in the terminal (see Printing Output).

Common conventions: 0 success, 1 general error, 2 incorrect usage (bad arguments). Codes must fit in 0 to 255 on Unix-like systems; larger values wrap around.

Use System.exit sparingly: only in main or a top-level error handler of a command-line tool. Calling it deep inside library code makes that code impossible to reuse or test, because it kills the whole JVM, including the test runner or web server that called it. Inside methods, throw an exception instead and let main decide the exit code.

main is just a method

Apart from its job as the entry point, main is an ordinary method. You can overload it, call it from other code, and have one in several classes. The launcher only cares about the class you start:

Java Calling another class's main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The launcher calls Main.main(String[]) because Main is the first class in the file. Tool also has a valid entry point, so in a real project you could start it with java Tool once it's compiled. Packaged applications name their main class in the JAR manifest (Main-Class:), which is how java -jar app.jar knows where to begin (see Build Tools: Maven and Gradle).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user runs java Main.java copy "my file.txt" backup. What is args.length?

    The quotes keep "my file.txt" as one argument and are removed by the shell, so args is {"copy", "my file.txt", "backup"}. The program name is not included.
  2. 2. What is args when a program is started with no arguments?

    The launcher always passes an array. With no arguments it's empty, so check args.length before reading args[0].
  3. 3. In Java 25, a class contains both void main() and static void main(String[] args). Which one does the launcher call?

    The launcher first looks for a main with a String[] parameter, static or not. Only if there is none does it use a no-argument main.
  4. 4. What exit code does a program have when main throws an uncaught IllegalStateException?

    An uncaught exception that escapes main prints a stack trace and the JVM exits with status 1.
  5. 5. Which method is NOT an entry point the launcher will use?

    The return type must be void. The other three are valid entry points in Java 25 (varargs is the same as String[], and main no longer has to be public or static).

Summary

  • The JVM starts a program by calling main; the classic form is public static void main(String[] args), where every keyword has a reason.
  • Java 25 allows compact source files and instance main methods that can be non-public, non-static and parameterless; a main(String[]) is preferred over main().
  • args holds the command-line words after the class or file name, as strings; it's empty (never null) when there are none, and args[0] is the first real argument.
  • Check args.length, provide defaults, parse numbers carefully and print a usage line on bad input.
  • Exit code 0 means success; an uncaught exception gives 1; System.exit(n) ends the JVM immediately with n and skips finally blocks.
  • main is otherwise a normal method: it can be overloaded and called from other code.

Next: Static vs Instance Methods, where you'll see what static really means and when a method should belong to an object instead.