Anatomy of a Java program

Java · Essentials · 8 min

You need to read the skeleton of a Java program fluently before anything else makes sense.

All Java code lives inside a class. When you launch a program, the JVM looks for a method with this exact signature and starts there:

public static void main(String[] args)
  • public — callable from outside the class (the JVM needs that).
  • static — belongs to the class itself, so no object has to be created first.
  • void — returns nothing.
  • String[] args — the command-line arguments, e.g. java App.java alice 42 gives args[0] == "alice".

Inside the method you write statements, each ending with a semicolon. Blocks of statements are grouped with braces { }. Java is case-sensitive: System and system are different names.

To print, use System.out.println(x) (adds a newline) or System.out.print(x) (does not). System.err is the error stream, useful for diagnostics.

Comments come in three flavours: // to end of line, /* block */, and /** Javadoc */ placed above classes and methods to generate API documentation.

Naming conventions are not enforced by the compiler but every Java developer follows them: classes in PascalCase, methods and variables in camelCase, constants in UPPER_SNAKE_CASE.

You may read about simplified "instance main methods" (void main() with no class). That is a preview feature in Java 21, so it needs --enable-preview; stick with the classic form for code that has to compile everywhere.

Example

/** A tiny program that greets everyone named on the command line. */
public class Greeter {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("usage: java Greeter.java NAME...");
            return;                       // leave main early
        }
        for (String name : args) {
            System.out.println("Hello, " + name + "!");
        }
    }
}
// java Greeter.java Ana Bo
// Hello, Ana!
// Hello, Bo!

Remember

  • Execution starts at public static void main(String[] args)
  • Statements end with ;, blocks use { }, and names are case-sensitive
  • Classes are PascalCase, methods and variables camelCase

Watch out for

  • Misspelling the main signature (e.g. Main or string[]): it compiles but the launcher reports that no main method was found.

Check yourself

  1. Why is `main` declared `static`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: dev.java/learn/getting-started/