Command Palette

Search for a command to run...

PHASE 0Beginner ~28 min· topic 5 of 8

Topic 0.5

Anatomy of a Java Program

In one line

Every Java program lives inside a class, starts running at the main method, and is made of statements that end with semicolons, grouped into blocks with curly braces. This topic explains every word of public static void main(String[] args) and of System.out.println, plus comments, names and the rules the compiler enforces.

Think of it like this

A letter in an envelope. The envelope has a name on the outside (the class Main). Inside is a letter with a heading that says "start reading here" (the main method). The letter is made of sentences, each ending with a full stop (statements ending with ;). Paragraphs are grouped together (blocks in { }). And there may be pencil notes in the margin that are not part of the letter (comments).

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Class
A named container for code, written class Name { ... }. Every Java program has at least one.
Method
A named group of statements that does one job, such as main. You run it by calling it.
Entry point
The place a program starts. In Java it is the main method.
Statement
One complete instruction, ending with a semicolon, such as System.out.println("Hi");.
Block
A group of statements inside curly braces { }.
Keyword
A word reserved by Java with a fixed meaning, such as public, class, static, void and int. You can't use it as a name.
Identifier
A name you choose for a class, method or variable, such as Main or score.
Comment
A note for humans that the compiler ignores. Starts with //, or sits between /* and */.
Command-line arguments
Extra words typed after the class name when running, such as java Main red blue. They arrive in args.
Package
A named group of related classes, like a folder. java.lang holds basics such as String, System and Math.

Step by step

01The whole program, labelled

Here is Hello World again, with every line explained by a comment. Read it top to bottom: a class, a method inside it, a statement inside the method.

Main.javawhole filejava
public class Main {                          // a class named Main; the file must be Main.java
    public static void main(String[] args) {  // the entry point: the JVM starts here
        System.out.println("Hello, World!");  // one statement: print a line
    }                                         // end of the main method
}                                             // end of the class
The whole program, labelleddiagram
Rendering diagram…

02The class: the box everything goes in

public class Main declares a class named Main. class is a keyword. public means any other code can use this class. Everything between the class's { and its matching } is the class body.

Java has no code outside classes. A Java 25 compact source file (Topic 11.5) looks like it does, but the compiler quietly wraps it in a class for you.

03The main method, word by word

public: the JVM is outside your class, so it needs permission to call main. static: when the program starts no objects exist yet, so main must belong to the class, not to an object. void: main returns nothing to the JVM (to report success or failure to the operating system, a program calls System.exit(code)).

main: the JVM searches for this exact name; Main or start won't do. (String[] args): one parameter named args, an array (a numbered list, Topic 3.8) of String values. You may rename args, or write String... args, and it still works; args is just the convention.

Main.javawhole filejava
public static void main(String[] args)
// |      |      |    |    |        |
// |      |      |    |    |        +-- parameter name (any name works)
// |      |      |    |    +-- type: an array of Strings
// |      |      |    +-- the name the JVM looks for
// |      |      +-- returns nothing
// |      +-- belongs to the class: no object needed
// +-- callable from outside the class

04Statements, semicolons and braces

The compiler doesn't care about line breaks or spaces between words: it uses ; to know where a statement ends, and braces to know where a block ends. You could put two statements on one line, or spread one statement over three lines. Humans care a lot, so the convention is one statement per line and four spaces of indentation per level.

Every { needs a matching }. A missing one gives reached end of file while parsing; an extra one gives class, interface, enum, or record expected. IDEs highlight matching braces to help.

05What System.out.println really is

Read it in pieces. System is a class in the package java.lang. Inside it, out is a static field: a value stored on the class, here an object of type PrintStream connected to standard output (your terminal or the browser's output pane). .println(...) calls the println method on that object.

The dots mean "go inside". System.out.println is "in System, take out, and call its println". print is the same without the line break. System.err is a second stream for error messages; terminals show it like normal output, but programs and tools can separate the two.

What System.out.println really isdiagram
Rendering diagram…

06Comments: notes the compiler skips

Write comments to explain why the code does something, not to repeat what it obviously does. // Close the file before deleting it, or Windows refuses is useful. // print hello above a line that prints hello is noise.

Comments can also switch a line off while you experiment: put // at its start, and the compiler ignores it. Javadoc comments /** ... */ sit above classes and methods and describe how to use them.

07Names and the case-sensitivity trap

Identifiers can contain letters, digits, _ and $, must not start with a digit, and must not be one of Java's keywords (about 50, such as class, int, if, new, return). my-score isn't allowed (the dash means minus); myScore is.

Conventions, which every Java programmer follows: classes in PascalCase (BankAccount), methods and variables in camelCase (totalPrice), constants in UPPER_SNAKE_CASE (MAX_SIZE). The compiler doesn't enforce these, but breaking them confuses every reader.

Try it yourself

  1. 1

    Pass arguments

    Save the args example as Main.java on your machine and run it with words after the file name. Predict the output first.

    terminal
    $ java Main.java red blue
    ── expected output ──
    Number of arguments: 2
    Argument: red
    Argument: blue
    main is finished, so the program ends.
  2. 2

    Squash and stretch

    Put the whole Hello World program on a single line and run it. It works. Now split System.out.println("Hi"); so that println and ("Hi"); are on separate lines. Still works. Then split the word println itself across two lines. That fails: a name can't contain a line break.

  3. 3

    Capital letters matter

    Change println to Println and compile. Read the error: it says it can't find a method Println(String) on something of type PrintStream, which is exactly what System.out is.

    terminal
    $ javac Main.java
    ── expected output ──
    Main.java:4: error: cannot find symbol
    System.out.Println("Bye");
    ^
    symbol: method Println(String)
    location: variable out of type PrintStream
    1 error

Code & diagrams

Comments of all three kinds New tab

None of the comments affect the output. The line switched off with // never runs.

Sign in to run this example in your browser.

Expected output

Hello!
Comments are ignored by the compiler.
The end.
Whitespace is for humans, case is for Java New tab

Odd spacing still compiles, because statements end at semicolons. score and Score are two different variables.

Sign in to run this example in your browser.

Expected output

One
Two
Three
score = 10
Score = 99
Looking at args New tab

The Run button passes no arguments, so args is an empty array. Locally, try java Main.java red blue.

Sign in to run this example in your browser.

Expected output

Number of arguments: 0
main is finished, so the program ends.
print vs println New tab
Sign in to run this example in your browser.

Expected output

Loading...
Ready.
Numbers print too: 42
Java 25: an instance main method Java 25+java

From Java 25, main may be non-static and have no parameters; the launcher creates the object for you. Old-style main still works and is what this course uses for runnable examples.

class Main {
    void main() {
        System.out.println("No public, no static, no String[] args.");
    }
}

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Forget static on main

Write public void main(String[] args) (no static), compile and run with JDK 21.

terminal
$ javac Main.java
java Main
── what you'll see ──
Error: Main method is not static in class Main, please define the main method as:
public static void main(String[] args)

Break #2

One brace too few

Delete the last } of the class.

terminal
$ javac Main.java
── what you'll see ──
Main.java:4: error: reached end of file while parsing
}
^
1 error

Break #3

Lowercase system

Write system.out.println(age); with a lowercase s.

terminal
$ javac Main.java
── what you'll see ──
Main.java:4: error: package system does not exist
system.out.println(age);
^
1 error

Myth vs fact

Myth

main must be the first thing in the class.

Fact

Members of a class can be in any order. The JVM finds main by name, not position.

Myth

Indentation matters to Java, like in Python.

Fact

Java ignores indentation. Braces and semicolons define the structure; indentation is for human readers.

Myth

The parameter must be called args.

Fact

Any name works: String[] input is fine. Only the type matters. args is the convention everyone uses.

Myth

System.out.println is a special command built into the language.

Fact

It is an ordinary method call: println on the PrintStream object stored in the static field out of the library class System.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    Launch protocol: up to Java 24 the launcher looks for public static void main(String[]) and reports missing or non-static forms with the messages above. Java 25 (JEP 512) also accepts non-public, non-static and parameterless main: it picks main(String[]) before main(), and for an instance main it calls the class's no-argument constructor first.

  • ▸

    System.out is a public static final PrintStream. Its println methods lock the stream, so concurrent prints don't interleave mid-line, but heavy printing in a hot loop is slow; use a StringBuilder or a BufferedWriter and print once (Topic 14.6). System.setOut can replace it, which is how test frameworks capture output.

  • ▸

    Keywords vs contextual keywords: class, int, static are reserved everywhere. var, record, yield, sealed, permits are contextual: special only in certain positions, so old code using them as variable names still compiles. The single underscore _ became a keyword in Java 9 and gained a meaning (unnamed variables) in Java 22.

  • ▸

    The return code of a Java process is 0 when main returns normally, 1 when an uncaught exception kills the main thread, or whatever you pass to System.exit(n). Scripts and CI pipelines read this code; never call System.exit from library code, because it kills the whole JVM, including servers.

Remember this

  1. 1

    A class is a named container for code: public class Main { ... }. In Java, all code lives inside classes. For now a class is just the box your program sits in; in Phase 4 you'll see that classes are also blueprints for objects.

  2. 2

    A method is a named group of statements that does one job. main is special: it is the entry point, the method the JVM calls first when you run java Main. The program ends when main finishes (as long as no other threads are still running, Topic 13.1).

  3. 3

    public static void main(String[] args) has five parts. public: code outside the class (the JVM) may call it. static: it belongs to the class itself, so the JVM can call it without creating an object first. void: it gives back no value. main: the exact name the JVM looks for. String[] args: a list of text values (the command-line arguments) typed after the class name, such as java Main red blue.

  4. 4

    A statement is one instruction, and it ends with a semicolon ;. A block is zero or more statements between curly braces { }. Braces always come in pairs, and they nest: the method's block sits inside the class's block. Indenting each level by four spaces doesn't change the meaning but makes the nesting visible to humans.

  5. 5

    Comments are notes for people, ignored by the compiler. // starts a comment that runs to the end of the line. /* ... */ can span several lines. /** ... */ is a Javadoc comment that tools turn into documentation web pages.

  6. 6

    Java is case-sensitive: Main, main and MAIN are three different names, and system.out.println is an error. Names (called identifiers) may use letters, digits, _ and $, can't start with a digit, and can't be a keyword such as class or int. By convention class names start with a capital (Main, BankAccount) and method and variable names start lowercase (main, totalPrice).

  7. 7

    System.out.println("Hi") reads right to left as: call the method println on the object System.out with the text "Hi". System is a class from the standard library, out is a field inside it holding the standard output stream (your terminal), and println prints a line. System needs no import because everything in the java.lang package is available automatically.

Explain it without notes

01

Explain each word in public static void main(String[] args).

02

What is the difference between a statement and a block?

03

Why is main static?

04

Break down System.out.println("Hi") into its parts.

Practice

01

Write a program with a Javadoc comment on the class, a block comment, and a line comment, that prints Comments done.

02

Write a program that prints how many command-line arguments it received, and run it locally with three arguments.

03

This program has three mistakes. Fix them: public class main { public static void Main(String[] args) { System.out.println("Fixed") } } (the file is Main.java).

Trade-offs

  • ↔

    Java's ceremony (class, public static void main) is extra typing for tiny programs, but it makes every program's structure the same and explicit. Java 25's compact source files remove the ceremony for small programs while keeping the rules for big ones.

  • ↔

    Comments help when they explain intent, but they can go out of date when code changes. Prefer clear names first, and comment the "why" that names can't say.

Done when you can

  • Done when you can explain every word of public static void main(String[] args).

  • Done when you can say what a class, method, statement and block are.

  • Done when you can write all three kinds of comments.

  • Done when you can explain System.out.println as class, field and method.

  • Done when you can fix missing semicolons, missing braces and wrong capital letters from the error message.