Sub topic 4
Compact Source Files
This chapter assumes you know basic Java syntax (variables, methods, control flow). It also assumes you know what a class, a field, and a method are, and that you can compile and run a program from the command line. You should be familiar with public static void main(String[] args). The previous chapters covered how the launcher chooses a main method and how instance main methods work. This chapter builds on both.
What a compact source file is
A compact source file is a .java file that contains top-level methods and fields, with no enclosing class declaration. Java 25 makes this feature final, so you don't need preview flags.
void main() {
IO.println("Hello, world!");
}Save this as Hello.java and it is a complete program. It has no public class, no static, and no String[] parameter.
The file is legal because the compiler wraps its members in a class for you. That class is the implicitly declared class, described next. The launcher then applies the main method selection rules you already know to that class.
The class the compiler declares for you
When a source file has a method or field outside any class, the compiler treats the whole file as the body of one class. The generated class has these properties:
- Its name is taken from the file name, so
Hello.javaproduces a class namedHello. - It is
final. - It extends
Object. - It lives in the unnamed package. A compact source file can't have a
packagedeclaration. - Other classes can't refer to it by name.
The last point matters in practice. You can't write new Hello() or Hello.greet() from another file. A compact source file is an entry point and not a reusable library class.
Because the file name becomes the class name, it must be a valid Java identifier. A file called my-app.java can't be turned into a class name.
The compiler also requires a launchable main method. If a compact source file has no main that the launcher could select, compilation fails. This catches the case where you wrote helper methods but forgot the entry point.
Top-level methods and fields
Top-level declarations become members of the implicit class. Without static, they are instance members, exactly as in an ordinary class.
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}
void main() {
IO.println(greet("Java"));
}Here greeting is an instance field and greet is an instance method. main is an instance method too, so the launcher creates an instance of Hello with its no-argument constructor and then calls main on it. That is why main can read greeting and call greet without any qualifier.
You can mix in static members when you want them:
static int square(int n) {
return n * n;
}
void main() {
IO.println(square(7));
}Both styles work. Use instance members by default in small programs, because that is the simpler form. Choose static when a method needs no state, as square does here.
Field initialization order
Field initializers run when the launcher constructs the instance, before main is called. This is the same as in any class. If an initializer throws an exception, main never runs.
int total = compute();
int compute() {
IO.println("initializing");
return 42;
}
void main() {
IO.println("total = " + total);
}This prints initializing first, then total = 42. This ordering is a common source of surprise when you treat a compact source file as a top-to-bottom script. It is a class, and the initializers run at construction.
What is imported automatically
In a compact source file, the compiler implicitly imports every package exported by the java.base module. That includes java.util, java.io, java.nio.file, java.util.stream, java.math, and java.time.
void main() {
List<String> names = List.of("Ada", "Grace");
for (String name : names) {
IO.println(name.toUpperCase());
}
}List needs no import java.util.List;. The same code inside an ordinary class would fail to compile without the import.
Three details are worth remembering:
- The automatic import applies only to compact source files. Ordinary classes still need explicit imports.
- Packages that are not in
java.base, such asjava.sqlorjava.net.http, still need an explicitimportstatement. You can writeimportstatements at the top of a compact source file as usual. - If two imported packages contain the same simple name, you get the usual ambiguity error. Add a single-type import to resolve it.
Console I/O with java.lang.IO
The class java.lang.IO provides static methods for simple console work. It lives in java.lang, so it is available in every Java file. You don't import it and you don't need a compact source file to use it.
| Method | What it does |
|---|---|
| `IO.println(Object)` | Prints a value and a line break to standard output |
| `IO.print(Object)` | Prints a value with no line break |
| `IO.readln()` | Reads one line from standard input |
| `IO.readln(String)` | Prints a prompt, then reads one line |
IO.readln replaces the usual Scanner boilerplate:
void main() {
String name = IO.readln("Your name: ");
IO.println("Hello, " + name + "!");
}IO.readln returns the line without its terminator. If standard input is closed, for example when you pipe in an empty file, it returns null. Check for null if your program may run unattended.
IO is deliberately small. It handles line-oriented text. For parsing numbers, formatting output, or reading large inputs, you still use Scanner, BufferedReader, or printf. Those classes are available in a compact source file without imports.
Helper types in the same file
Classes, records, interfaces, and enums declared in a compact source file become members of the implicit class. They are nested types of the generated class.
record Point(int x, int y) {}
void main() {
IO.println(new Point(1, 2));
}This prints Point[x=1, y=2]. Because Point is a member of the implicit class, main can use it by its simple name.
A nested record is implicitly static, so it can't touch the fields of the enclosing instance. A nested class that is not declared static is an inner class. It holds a reference to the enclosing instance and can read greeting or call greet. If you want a plain helper that doesn't depend on the outer instance, declare it static, or use a record, enum, or interface.
Running and compiling
You have two ways to run the file.
java Hello.java
javac Hello.java
java HelloThe first command uses the source launcher. It compiles the file in memory and runs it, and writes no .class file. The other two commands compile to Hello.class and then run that class by name. Note that java Hello takes no .java extension, while java Hello.java must include it.
The source launcher is convenient for scripts and experiments. Compile with javac when you want to package the result or check that it builds in a normal pipeline.
Command-line arguments reach your program only if you declare a main method with a String[] parameter. A compact source file may declare void main(String[] args). The launcher prefers a method that takes String[] over one that takes none, as you saw in the selection rules.
Restrictions and pitfalls
- No
packagedeclaration. The implicit class is always in the unnamed package. - No references from other files. The class can't be named elsewhere, so you can't share its methods through that route.
- A main method is required. Without a launchable one, compilation fails.
- File name matters. It becomes the class name, so it must be a valid identifier.
- Members are instance members by default. A field initializer that has side effects runs at construction.
- Name clashes. A top-level method named like a
java.langorjava.utilclass does not conflict with it, but a nested type with the same name as an imported type shadows the import.
Exercise
A file named Counter.java contains int count = 10; and void main() { IO.println(count++); IO.println(count); }. It is run with java Counter.java. What does it print, and why can main use count without static?
Show answer
It prints 10 and then 11. The compiler wraps the members in an implicit class named Counter. Because main is an instance method, the launcher creates an instance with the no-argument constructor, initializes count to 10, and calls main on it. count++ returns 10 and then increments, so the second line shows 11.
Exercise
Your compact source file uses List<String> with no import and compiles. You copy the same code into a file that declares public class Demo { ... } and it fails. Why, and what is the fix?
Show answer
Only compact source files implicitly import the packages exported by java.base. An ordinary class needs its own imports, so add import java.util.List;.