Sub topic 2
Anatomy of a Java Program
This chapter assumes you can use a command line or terminal and that you have read the previous chapter on how the JVM runs Java code. You do not need prior programming experience. We will take one small Java program and examine every piece of it: what each part is called, what it does, and what rules Java applies to it.
The Whole Program, Then the Pieces
Here is the smallest useful Java program. Save it in a file named Main.java.
public class Main {
public static void main(String[] args) {
System.out.println("Hello from inside main!");
}
}Every Java program is made of classes. A class is a container for code. Inside a class, you put methods. A method is a named block of instructions, like a recipe with a name. This program has one class, Main, containing one method, main.
The Class Declaration
public class Main {This line has three parts:
publicis an access modifier. It is a word that controls who can see this class.publicmeans "anyone can use this." For now, we always usepublicfor our main class.classis a keyword. A keyword is a word reserved by Java with a special meaning.classannounces that you are defining a class.Mainis the name you choose. Names can contain letters, digits, and underscores, but cannot start with a digit. By convention (an agreed style, not a rule), class names start with a capital letter.
The { that follows opens the body of the class. Everything between { and the matching } belongs to the class. Java uses braces to group code, and everything inside them is indented for readability — the indentation is not required, but almost all Java programmers use it.
One hard rule: the file name must match the public class name. A public class Main must live in Main.java. If they differ, the compiler rejects your program.
The main Method: The Entry Point
public static void main(String[] args) {This line looks dense, so let us take it apart word by word.
| Piece | Meaning |
|---|---|
| `public` | Anyone can call this method — required so the JVM can call it. |
| `static` | The method belongs to the class itself, not to an object of the class. The JVM can call it without creating anything first. |
| `void` | The method returns nothing. |
| `main` | The exact name the JVM looks for when starting a program. |
| `String[] args` | A parameter: an array of text values passed in from the command line. |
Together, this exact signature tells the JVM: "start executing here." If the name is misspelled (Main instead of main), or the signature does not match, the JVM reports an error such as Main method not found when you try to run the program.
The String[] args part deserves a closer look. When you run:
java Main first secondthe words after the class name are delivered to your program as a list of text values. This small program prints them:
public class Main {
public static void main(String[] args) {
System.out.println("Count: " + args.length);
System.out.println("First: " + args[0]);
}
}Run with java Main apple, it prints Count: 1 and First: apple. Run with no arguments, args.length is 0 — and args[0] would fail, because there is no first element. Counting from zero rather than one is a habit Java shares with most languages; keep it in mind.
Statements and the Semicolon
Inside main, the work happens in statements. A statement is one complete instruction.
System.out.println("Hello from inside main!");System.outis Java's built-in connection to the standard output, normally your terminal.printlnis a method on it that prints text and moves to a new line.- The dot in
System.out.printlnmeans "reach inside": fromSystem, getout, then fromout, callprintln. - The
;(semicolon) ends the statement. Every statement in Java ends with a semicolon. Forgetting it is the single most common beginner error, and the compiler's message for it (';' expected) points at the next line, not the broken one — so when you see it, check the line above.
Not everything ends with a semicolon. Class and method declarations end with braces, not semicolons:
public class Main { // no semicolon here
public static void main(String[] args) { // no semicolon here
System.out.println("done"); // semicolon here
} // no semicolon here
} // no semicolon hereA useful habit: whenever you type an opening {, type the closing } immediately, then fill in the middle. This keeps braces balanced and avoids the infamous "too many or too few curly braces" errors.
Comments
Comments are notes for human readers; Java ignores them completely.
// A single-line comment runs to the end of the line.
/*
A block comment can span
as many lines as you like.
*/
public class Main {
// main is where the JVM starts running the program.
public static void main(String[] args) {
System.out.println("Running"); // trailing comment
}
}Use comments to explain why code does something, not to restate what it obviously does.
Blocks and Nesting
Java programs nest like boxes: statements sit inside methods, methods sit inside classes, and a statement can contain its own block. Each opening brace must have exactly one closing brace, and the compiler will refuse your program if they do not match up.
When the compiler reports a brace error, count your braces by hand. Editors color-code matching pairs, which makes this much easier.
Whitespace and Style
Java does not care about line breaks or spaces (except inside text in quotes). These two are identical to the compiler:
int total = 5; System.out.println(total);int total = 5;
System.out.println(total);The second is far easier to read, and readability is what you should optimize for. The widely used Java conventions are:
- Class names:
UpperCamelCase— each word capitalized. - Method names:
lowerCamelCase— first word lowercase. - Indent one level (usually 4 spaces) for each new brace.
A Slightly Larger Program
Everything above appears together here. Read it top to bottom and name each piece before moving on.
public class Main {
public static void main(String[] args) {
System.out.println("Starting the program.");
System.out.println("Arguments given: " + args.length);
System.out.println("Done.");
}
}- File:
Main.java(matches the class name). - One class,
Main, markedpublic. - One method,
main, with the exact signature the JVM requires. - Three statements, each ending in a semicolon, executed in order from top to bottom.
That last point matters: inside a method, Java runs statements in the order they are written, top to bottom, unless you use the control-flow tools covered in a later chapter.
Common Errors at This Stage
| Error message | Usual cause | Fix |
|---|---|---|
| `class Main is public, should be declared in a file named Main.java` | File name and class name differ | Rename the file or the class so they match |
| `';' expected` | Missing semicolon on the previous statement | Add the semicolon |
| `Main method not found` | `main` misspelled, or the signature changed | Restore the exact `public static void main(String[] args)` line |
| `reached end of file while parsing` | A brace is missing somewhere | Check that every `{` has a matching `}` |
Exercise
What happens if you name the file program.java but the class inside it Main?
Show answer
The compiler refuses to compile it, reporting that a public class must be declared in a file with the same name. Rename the file to Main.java.
Exercise
In public static void main(String[] args), what does void mean?
Show answer
The method returns no value to whoever called it. It performs its work (printing, in our examples) and finishes without handing back a result.
Exercise
You run java Main hello against the argument-printing program from this chapter. What is printed?
Show answer
Two lines: Count: 1 and First: hello, because the one argument lands in the args array at index 0.