Sub topic 3
Running and Compiling a Compact Source File
This chapter assumes Java 25 or later, basic Java syntax, and familiarity with javac and java. A compact source file has top-level methods and fields instead of an explicit class declaration.
Running and compiling a compact source file
Save this as Hello.java:
void main() {
IO.println("Hello, world!");
}Run it directly with the Java source launcher:
java Hello.javaTo compile it first, use javac:
javac -d out Hello.java
java -cp out HelloThe compiler creates an implicitly declared class named Hello, based on the file name.
Adding helper classes, records, and interfaces
Helper types can appear in the same file. They become members of the implicit class.
interface Printable {
String text();
}
record Point(int x, int y) implements Printable {
public String text() {
return "Point(" + x + ", " + y + ")";
}
}
class Formatter {
String format(Printable value) {
return value.text();
}
}
void main() {
IO.println(new Formatter().format(new Point(1, 2)));
}Growing a script into a full class
When the program needs a clearer boundary, wrap its members in an explicit class:
public class Hello {
void main() {
IO.println("Hello, world!");
}
}The behavior remains the same. The file now uses ordinary class syntax and can later gain constructors, interfaces, or separate source files.
Restrictions and common pitfalls
- Use Java 25 or later for the final feature.
- A compact file must not also declare its enclosing explicit class.
- Top-level methods are members of the implicit class, not independent package-level functions.
- The compiled class name comes from the source file name, so choose the file name carefully.
- An IDE or build tool may require explicit class syntax or special Java 25 support.
From preview to final: version history
The feature appeared as a preview in Java 21, received further previews in Java 22, 23, and 24, and became final in Java 25. Code intended for Java 25 no longer needs preview flags.
Exercise
Which command compiles Hello.java into the out directory?
Show answer
javac -d out Hello.java