Sub topic 12
Restrictions and Common Pitfalls
Compact source files and instance main methods remove ceremony, but they come with rules. Most of the errors that beginners and experienced developers hit come from forgetting what the compiler generates behind the scenes. This chapter lists those rules and shows how to fix each error.
This chapter assumes you know Java syntax, the difference between static and instance members, and the difference between a top-level class and a nested class. It also assumes you know the earlier chapters' vocabulary: launcher, compact source file, implicit class. Examples need Java 25. On Java 21 to 24 the features are preview features, so you must pass --enable-preview and a matching --source option to use them.
The launcher's selection order, revisited
Many pitfalls come from not knowing which method the launcher picks. When a class has several candidates, the launcher checks them in a fixed order and stops at the first match:
static void main(String[] args)static void main()void main(String[] args)(instance)void main()(instance)
A candidate must return void and must not be private. It can be public, protected, or package-private.
Two consequences follow.
First, a static method always beats an instance method. If you leave an old public static void main(String[] args) in a class and add void main(), the old one runs and your new one is ignored. The launcher raises no warning.
Second, the instance path needs more than a method. The class must be non-abstract, it must be a top-level class (or a static nested class), and it needs a non-private constructor with no parameters. A class whose only constructor takes arguments compiles fine and then fails at launch:
class Broken {
private final String label;
Broken(String label) {
this.label = label;
}
void main() {
IO.println(label);
}
}Running this reports that the launcher cannot create an instance, because no accessible no-argument constructor exists. Add a no-argument constructor, or switch to a static main.
A compact source file must have a main method
An implicitly declared class exists to be launched. If a compact source file declares top-level members but no launchable main, the compiler rejects the file:
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}This file declares a field and a method but no entry point, so javac fails with an error. Library code that has no entry point belongs in an ordinary named class.
The check applies to the same selection rules as above. A top-level method named main with the wrong return type, or marked private, does not count.
What the implicit class cannot do
The compiler wraps your members in a class you never name. That class is deliberately limited.
| Property | Rule |
|---|---|
| Name | Taken from the file name, so `Hello.java` gives `Hello` |
| Package | Always the unnamed package |
| Superclass | Always `Object` |
| Interfaces | None. You cannot write `implements` |
| Modifiers | The class is `final` |
| References | Other source code cannot refer to it by name |
| Instances | You cannot write `new` for it yourself. The launcher creates the one instance |
The practical effects are these.
- No
packagedeclaration. A file with top-level methods or fields cannot also declare a package. If your build tool expects every source file under a package directory, compact files do not fit. - No inheritance. You cannot extend another class or implement an interface at the top level. If you need that, write an explicit class (see the chapter on growing a script into a full class).
- Not reusable. A second file cannot call
Hello.greet(...), because the implicit class has no usable name. Code you want to share needs a real class. - The file name matters. The class name comes from the file name, so the file name must be a valid Java identifier. Something like
hello-world.javafails when you compile it withjavac.
Top-level members are instance members
A top-level field or method in a compact source file is an instance member of the implicit class. It is not static unless you write static. This matters in two places.
Static methods cannot see instance fields. If you declare a top-level static method, it cannot touch top-level fields that are not static:
int total = 0;
static void add(int amount) {
total += amount; // compile error: non-static variable total
}
void main() {
add(5);
IO.println(total);
}The simplest fix is to drop static from add. Alternatively, make total static too. Mixing the two styles in one file is the main source of confusing errors, so choose one style per file. For a small script, writing no static keywords at all is the least surprising choice.
Fields are initialized when the launcher creates the instance. The launcher builds the instance first, so every field initializer runs before main begins. A field initializer that throws an exception stops the program before main is entered, and the stack trace will not show main.
Helper classes are inner classes
A class declared in a compact source file is not a separate top-level class. It becomes a member of the implicit class. A plain class member is an inner class, which means each instance needs an enclosing instance of the implicit class. This works in instance code:
class Counter {
int value;
}
void main() {
Counter c = new Counter();
c.value++;
IO.println(c.value);
}It breaks in a static context, where no enclosing instance exists:
class Counter {
int value;
}
static Counter make() {
return new Counter(); // compile error: no enclosing instance
}
void main() {
IO.println(make().value);
}Three fixes are available:
- Remove
staticfrommake. - Declare the helper
static class Counter. - Use a
record, anenum, or aninterface. These are implicitly static when nested, so they work everywhere.
record Counter(int value) {}
static Counter make() {
return new Counter(0);
}
void main() {
IO.println(make());
}This prints Counter[value=0].
There is one more naming trap. A nested type cannot have the same simple name as its enclosing class. In a file called Point.java, declaring record Point(int x, int y) {} fails, because the implicit class is already named Point. Pick a file name that differs from every type declared inside it.
Automatic imports can surprise you
Compact source files implicitly import all packages exported by the java.base module. That is why List, Map, and Path need no import statement. Several limits apply:
- Only
java.baseis covered. Classes from other modules, such asjava.sql.Connectionorjava.net.http.HttpClient, still need animportstatement. - A type you declare in the file shadows an imported type with the same name. If you write
record List(int size) {}, your record replacesjava.util.Listeverywhere in that file, andList.of(...)stops compiling. - An explicit single-type import such as
import java.util.Date;beats the automatic imports when two types share a name. - The automatic import exists only in compact source files. In an ordinary class, you still import
java.util.Listyourself.
The class java.lang.IO is different. Because it lives in java.lang, you can use it from any class, compact or not. It is not imported statically, so you must write IO.println, not println.
Console I/O pitfalls
IO.readln reads one line of text and returns null at end of input. A program that reads in a loop must check for that, or it will fail with a NullPointerException when the input is piped from a file:
void main() {
String line = IO.readln("> ");
while (line != null && !line.isBlank()) {
IO.println("You typed: " + line);
line = IO.readln("> ");
}
IO.println("Done.");
}Other points to remember:
IO.readlnreturns aString. Parse numbers yourself withInteger.parseInt, and handleNumberFormatException.IO.printdoes not add a newline, andIO.printlndoes. Mixing them can leave a prompt on the same line as the output.IOis meant for simple programs. For formatted output, useString.formatand pass the result toIO.println. For anything complex, continue withSystem.out,Scanner, orBufferedReader.
Command-line arguments
A no-argument main() cannot see command-line arguments. If your script needs them, use the one-parameter form. It works as an instance method in a compact file:
void main(String[] args) {
if (args.length == 0) {
IO.println("Usage: java Greet.java <name>");
return;
}
IO.println("Hello, " + args[0] + "!");
}Run it with java Greet.java Ada. The arguments after the file name go to the program, not to java.
Version mismatches
If you run these examples on a JDK older than 25 without preview options, the compiler reports that instance main methods or unnamed classes are a preview feature, or the launcher reports that it cannot find main(String[]). Check java -version first. If you must stay on Java 21 to 24, add --enable-preview --source N, where N is your JDK's feature release number, and expect small differences, such as a different name for the implicit class in older preview documentation and IO being absent or needing a static import in some releases.
Quick checklist
Before asking why a compact source file fails, check these in order:
- Is there a launchable, non-private
mainthat returnsvoid? - Does the JDK report version 25 or later?
- Is a stale
static mainhiding your instancemain? - Are
staticand non-static members mixed in the same file? - Do helper classes need to be
staticor records? - Does the file name clash with a type declared in the file?
- Does the file need a
packagedeclaration,extends, orimplements? If so, move to an explicit class.
Exercise
The file Counter.java below fails to compile. Name the two separate reasons, and give a version that fixes both. record Counter(int value) {} void main() { IO.println(new Counter(3)); }
Show answer
The record is named Counter, the same as the implicit class derived from Counter.java, and a nested type cannot share its enclosing class's name. Rename the record, for example to Tally, or rename the file. The prior chapter's rule that a compact file needs a main method is satisfied here, so the name clash is the only compile error. The second problem appears only on JDKs before 25, where the file needs --enable-preview. A fixed version is: record Tally(int value) {} followed by void main() { IO.println(new Tally(3)); }, which prints Tally[value=3].
Exercise
A class has both "public static void main(String[] args)" and "void main()". Which one does the launcher run, and why might this surprise someone who just added the second method?
Show answer
The launcher runs the static main(String[]) method, because static candidates with a String[] parameter are checked first. Someone who added void main() expecting it to run will see the old method execute and get no warning.