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
mainmethod. - 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,voidandint. You can't use it as a name. - Identifier
- A name you choose for a class, method or variable, such as
Mainorscore. - 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 inargs. - Package
- A named group of related classes, like a folder.
java.langholds basics such asString,SystemandMath.
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.
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 class02The 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.
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 class04Statements, 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.
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
Pass arguments
Save the
argsexample asMain.javaon 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: 2Argument: redArgument: bluemain is finished, so the program ends. - 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 thatprintlnand("Hi");are on separate lines. Still works. Then split the wordprintlnitself across two lines. That fails: a name can't contain a line break. - 3
Capital letters matter
Change
printlntoPrintlnand compile. Read the error: it says it can't find a methodPrintln(String)on something of typePrintStream, which is exactly whatSystem.outis.terminal$ javac Main.java── expected output ──Main.java:4: error: cannot find symbolSystem.out.Println("Bye");^symbol: method Println(String)location: variable out of type PrintStream1 error
Code & diagrams
None of the comments affect the output. The line switched off with // never runs.
Expected output
Hello!
Comments are ignored by the compiler.
The end.Odd spacing still compiles, because statements end at semicolons. score and Score are two different variables.
Expected output
One
Two
Three
score = 10
Score = 99The Run button passes no arguments, so args is an empty array. Locally, try java Main.java red blue.
Expected output
Number of arguments: 0
main is finished, so the program ends.Expected output
Loading...
Ready.
Numbers print too: 42From 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.
Break #2
One brace too few
Delete the last } of the class.
Break #3
Lowercase system
Write system.out.println(age); with a lowercase s.
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 parameterlessmain: it picksmain(String[])beforemain(), and for an instance main it calls the class's no-argument constructor first. - ▸
System.outis apublic static final PrintStream. Itsprintlnmethods lock the stream, so concurrent prints don't interleave mid-line, but heavy printing in a hot loop is slow; use aStringBuilderor aBufferedWriterand print once (Topic 14.6).System.setOutcan replace it, which is how test frameworks capture output. - ▸
Keywords vs contextual keywords:
class,int,staticare reserved everywhere.var,record,yield,sealed,permitsare 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
mainreturns normally, 1 when an uncaught exception kills the main thread, or whatever you pass toSystem.exit(n). Scripts and CI pipelines read this code; never callSystem.exitfrom library code, because it kills the whole JVM, including servers.
Remember this
- 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
A method is a named group of statements that does one job.
mainis special: it is the entry point, the method the JVM calls first when you runjava Main. The program ends whenmainfinishes (as long as no other threads are still running, Topic 13.1). - 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 asjava Main red blue. - 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
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
Java is case-sensitive:
Main,mainandMAINare three different names, andsystem.out.printlnis an error. Names (called identifiers) may use letters, digits,_and$, can't start with a digit, and can't be a keyword such asclassorint. By convention class names start with a capital (Main,BankAccount) and method and variable names start lowercase (main,totalPrice). - 7
System.out.println("Hi")reads right to left as: call the methodprintlnon the objectSystem.outwith the text"Hi".Systemis a class from the standard library,outis a field inside it holding the standard output stream (your terminal), andprintlnprints a line.Systemneeds noimportbecause everything in thejava.langpackage is available automatically.
Explain it without notes
Explain each word in public static void main(String[] args).
What is the difference between a statement and a block?
Why is main static?
Break down System.out.println("Hi") into its parts.
Practice
Write a program with a Javadoc comment on the class, a block comment, and a line comment, that prints Comments done.
Write a program that prints how many command-line arguments it received, and run it locally with three arguments.
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.printlnas class, field and method.Done when you can fix missing semicolons, missing braces and wrong capital letters from the error message.