Skip to content

What breaks main, and command-line arguments

โ˜• Java 17 ยท Writing Your First main() Method ยท 2/3

A valid main is public static void main(String[] args), with a few allowed variations. Here's what goes wrong when it isn't.

It compiles, but it doesn't run

Each of these methods compiles without any error. The class is fine: it just has no entry point the JVM can use.

public void main(String[] args) { }                   // โŒ missing static
public static int main(String[] args) { return 0; }   // โŒ must return void
public static void main(int[] args) { }               // โŒ must take String[] or String...
public static void Main(String[] args) { }            // โŒ Main is not main

The problem shows up only when you launch the class:

$ java StreamingApp
Error: Main method is not static in class StreamingApp, please define the main method as:
   public static void main(String[] args)

This difference between compiling and running matters: a class doesn't need a main to compile. Only the class you launch needs one.

Passing data at launch

Every word typed after the class name becomes one element of args:

public class StreamingLauncher {
    public static void main(String[] args) {
        System.out.println("Args count: " + args.length);
        System.out.println("First arg: " + args[0]);
    }
}
$ java StreamingLauncher Netflix Premium
Args count: 2
First arg: Netflix
  • Spaces separate the values: args[0] is Netflix, args[1] is Premium.
  • Indexes start at 0.
  • args.length gives the number of arguments.

Check before you read

Launch the same program without arguments and args is an empty array. Reading args[0] stops the program:

$ java StreamingLauncher
Args count: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

The fix is to check args.length first, and stop with a helpful message when something is missing:

if (args.length < 1) {
    System.out.println("Usage: java StreamingLauncher <name>");
    return;   // leaves main: the program ends cleanly
}
System.out.println("First arg: " + args[0]);

This is defensive programming: guard first, then act. The lab uses exactly this pattern to launch our streaming platform.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

โ† The main signature ยท Next: the lab โ†’