Classes, methods and blocks
The four things every Java program is made of, why one file can produce three class files, and the block that decides what exists.
Every Java program is the same four things nested inside each other: a class holds methods, a method holds statements, and statements are grouped into blocks. Once you can name those in a file you have never seen, reading unfamiliar Java stops being decoding and starts being reading.
The smallest complete program, named part by part
public class Greet { // a class
public static void main(String[] args) { // a method
String who = "world"; // a statement
System.out.println("hello " + who); // another
}
}class Greet— a named thing that holds code. In Java nothing lives outside one; there are no free-floating functions.main— a method: a named block of statements you can call, with a list of parameters and a return type.String who = "world";— a statement. It ends with a semicolon, which is how the compiler knows where it stops. Newlines mean nothing to Java.{ ... }— a block. Every pair groups statements and, as the next section shows, decides what is visible.
The file is Greet.java because a public class must be in a file of its own name. That is a rule about public specifically; a non-public class can live anywhere.
One file does not mean one class
That last rule is often mis-learned as one file, one class. Compile a file with a nested class and an anonymous one in it:
public class Shape {
static class Inner { }
public static void main(String[] a) {
Runnable r = new Runnable() { public void run() { } };
}
}$ javac Shape.java
$ ls *.class
Shape$1.class Shape$Inner.class Shape.classThree class files from one source file. The compiler's unit is the class, not the file, and the naming is worth recognising: Outer$Inner for a named nested class, Outer$1 for an anonymous one, numbered in the order they appear.
You will meet those exact names again in a stack trace. A frame reading OrderService$1.run is an anonymous class inside OrderService, and now it is a place you can find rather than a puzzle.
A block decides what exists
Braces are not only punctuation. Anything declared inside a block stops existing when the block ends:
{
int insideTheBlock = 1;
System.out.println("inside: " + insideTheBlock); // fine
}
System.out.println(insideTheBlock); // not fineScope.java:4: error: cannot find symbol
System.out.println(insideTheBlock);
^
symbol: variable insideTheBlockThat is why a variable declared in a for loop's header is gone after the loop, and why declaring one inside an if and using it after does not compile. The rule is the same everywhere: a name lives from its declaration to the closing brace of the block it is in, and nowhere else.
It is also a tool. Declaring a variable in the smallest block that needs it is how you stop it being reused by accident twenty lines later — which the local variables lesson takes further.
Expressions and statements are different things
Worth separating early, because error messages assume you know:
- An expression produces a value.
2 + 2,name.length(),age > 18. - A statement does something. An assignment, a method call used for its effect, an
if, areturn.
Some expressions can be statements on their own — a method call is the usual case. Most cannot: 2 + 2; is not a legal statement, and the compiler says not a statement, which reads as nonsense until you know it means this produces a value and does nothing with it.
The distinction is why if (x = 5) fails in Java and quietly works in C: x = 5 is an expression producing 5, an int where a boolean is required. Java's type system catches it; that is a deliberate design decision and not an accident.
Keywords and identifiers
Keywords are the roughly fifty words the language reserves — class, public, static, if, return, new, final. You cannot use one as a name; that is the entire rule, and the compiler enforces it immediately.
Three details worth carrying:
true,falseandnullare not keywords, they are literals. The effect is the same: you cannot name a variablenull.- Some words are keywords only in context.
var,record,sealed,yieldandpermitswere added without breaking code that used them as names, so a variable calledrecordstill compiles. They are called contextual keywords. gotoandconstare reserved and unused. They exist in the keyword list so that a program using them as names fails clearly rather than working and then breaking if the words are ever given meaning.
Identifiers — your names — may contain letters, digits, _ and $, and may not start with a digit. The mechanical rule is uninteresting; the convention is not, and the naming lesson covers what a reviewer actually reads. One piece of it belongs here: $ is legal and reserved by convention for generated code, which is why the compiler used it for Shape$Inner. Do not put it in a name you write.
Three modifiers you will read before you write
public, private, static and final you will write on day one. Three others appear in code you read long before you need them, and each means something quite specific:
transientmarks a field that Java serialization must skip — a cache, a lock, a connection, a password — and that comes back asnullor zero after deserialisation. It means nothing outside serialization, and the I/O course's serialization section is where it gets its full story (and its warning).volatilemarks a field whose reads and writes go straight to main memory with ordering guarantees, so a value one thread writes is seen by another. It is not a lock and does not makecount++atomic; the concurrency course's memory-model lesson explains what it does promise, and it is the modifier most often written by people who neededAtomicIntegerorsynchronizedinstead.nativemarks a method with no body in Java: the implementation is in a shared library loaded withSystem.loadLibrary, called through JNI. You will see it in the JDK's own sources (System.arraycopy,Object.hashCode) and in libraries that wrap C code; you will almost never write one, and the modern-Java course's Foreign Function & Memory API is what replaces writing them.
Two more that look like modifiers and are not: strictfp (a no-op since Java 17, when floating point became strict everywhere) and synchronized on a method, which is a lock on this and belongs to the concurrency course.
Comments, and the two kinds worth writing
// to the end of the line
/* across
several lines */
/** a documentation comment, read by javadoc and by your IDE */The compiler discards all three. They exist for the next person, who is usually you.
The useful distinction is not the syntax, it is what the comment says:
// add one to i
i++; // noise: it repeats the code and rots when the code changes
// Retry three times: the payment provider returns 503 during their
// nightly maintenance window and recovers within ~2 seconds.The second cannot be recovered from the code at any price. Comment the why, and the surprising: a workaround for somebody else's bug, a constant that came from a measurement, a decision that looks wrong and is not.
The third form, /** ... */, is different in kind because it is published. It becomes the tooltip in every caller's IDE, so it is written for someone who will never open your file: what the method does, what its parameters mean, what it returns, and what it throws.
Under the hood: how javac picks between two methods with the same name
A class can declare several methods named pick, each taking a different parameter type — overloading — and every call to pick(x) must resolve to exactly one of them, decided entirely by javac at compile time, before the program ever runs. (This is a different question from overriding, where a subclass replaces a method it inherited — that resolution happens at run time, based on the actual object, and belongs to the classes lesson later in this course.) The rule the JLS gives (§15.12) is not "closest match" in some vague sense; it runs in three strict phases, and stops at the first one that finds an applicable method:
- Phase 1 — strict invocation. Can the argument be passed with no boxing, no unboxing, and no varargs — only widening primitive conversions (
int→long) or widening reference conversions? If more than one method qualifies, the most specific one wins: the one whose parameter type every other applicable method's parameter type can be assigned to. - Phase 2 — loose invocation. Only runs if phase 1 found nothing. Same search, but boxing and unboxing are now allowed (
int→Integer). - Phase 3 — variable arity. Only runs if phase 2 found nothing. Varargs methods are now candidates.
static void pick(Object o) { System.out.println("Object"); }
static void pick(long l) { System.out.println("long"); }
static void pick(Integer i) { System.out.println("Integer"); }
static void pick(int... i) { System.out.println("int..."); }
pick(5); // an int literal5 is an int. Phase 1 looks for a method reachable with no boxing and no varargs: pick(long) qualifies (int widens to long with no boxing at all), pick(Object) does not (that needs boxing to Integer and a reference conversion), pick(Integer) does not (boxing), and pick(int...) is not even considered yet. Phase 1 found exactly one applicable method, so the search stops there — pick(long) is called, and pick(Integer), despite looking like the "obvious" match for an int, is never even in contention. Delete the long overload and the same call resolves differently: pick(Integer) and pick(Object) both need boxing, so they compete in phase 2, and Integer wins there as more specific than Object; pick(int...) never gets a look because phase 2 already found an applicable method. The order of the phases, not "which looks closest," is the whole rule.
Under the hood: what runs before the constructor body
A class can mix field initializers (int x = 1;) and bare instance initializer blocks ({ ... }, no keyword, distinct from the static { ... } blocks the loading lesson in the programming-foundations course covers). Both run every time an instance is created, and the JLS is explicit about the order (§12.5): field initializers and instance initializer blocks run in the order they are written in the source, top to bottom, and all of them run before the constructor body — inserted, conceptually, at the very top of it, after the implicit or explicit call to the superclass constructor.
class InitOrder {
int x = log("field x");
{ log("instance block 1"); }
int y = log("field y");
InitOrder() {
log("constructor body");
}
{ log("instance block 2"); }
static int log(String s) {
System.out.println(s);
return 0;
}
}
new InitOrder();Nothing about where in the class a block or a field is declared changes when it runs relative to the constructor — only its position relative to the other initializers matters, which is why the second instance block, written after the constructor in the source, still runs before the constructor body executes. This is also why a field initializer can safely reference an earlier field but not a later one declared with var-inferred or self-referential logic: at the point each initializer runs, only the initializers above it have executed.
Try it yourself
Trace an overload call before running it
static void handle(Object o) { System.out.println("Object"); }
static void handle(Integer i) { System.out.println("Integer"); }
static void handle(long l) { System.out.println("long"); }
handle(3);Which overload is called, and which phase decides it? Now remove handle(long) — does the answer change, and why?
Answer
With all three present: handle(long), in phase 1 — 3 is an int, and widening it to long needs no boxing, so phase 1 already finds an applicable method and stops before boxing is even considered. Remove handle(long): phase 1 finds nothing (both remaining methods need boxing), so phase 2 runs and both handle(Object) and handle(Integer) are applicable; Integer is more specific (every Integer is an Object, not the reverse), so handle(Integer) wins.
Misconceptions
- "The compiler picks the overload that matches best overall." It picks the first phase that has an applicable method at all, then the most specific one within that phase — a method from a later phase is never even compared against one from an earlier phase, however well it would have fit.
- "Instance initializer blocks are unusual and rarely matter." They are what a field initializer with a non-trivial expression compiles into, conceptually, and they are exactly where record compact constructors and some generated code place validation — understanding their order explains output that otherwise looks like the constructor ran twice.
Sources
- The Java Language Specification, §15.12.2 (Compile-Time Step 2: Determine Method Signature) — the three phases of applicability and most-specific-method selection.
- The Java Language Specification, §12.5 (Creation of New Class Instances) — the order of field initializers, instance initializer blocks and constructor bodies.