Sub topic 9
Running and Compiling a Compact Source File
This chapter assumes you know basic Java syntax and have compiled and run a traditional public static void main(String[] args) program from the command line. You should also have read the earlier chapters of this tutorial, which cover compact source files and the implicitly declared class. Here the focus is the tools. You will learn how to run a compact source file, how to compile it, what each route produces, and where the two behave differently.
Both features are final in Java 25. You need a JDK 25 or later, and no --enable-preview flag.
Two ways to run the same file
Take this file, saved as Hello.java:
void main() {
IO.println("Hello, world!");
}You can run it in two ways:
java Hello.java
javac Hello.java
java HelloThe first command uses the source launcher. This is the java command's source-file mode, which compiles the file in memory and runs it at once. It writes no .class file to disk.
The second route has two steps. javac compiles the file and writes Hello.class. Then java Hello loads that class by name, as with any compiled program.
The java command chooses its mode from the argument. If the argument ends in .java, it uses source-file mode. Otherwise it treats the argument as a class name.
What the compiler names the class
A compact source file has no class declaration, so the compiler declares one for you. The name of that class comes from the file name, minus the .java extension. Hello.java yields a class named Hello. This is why java Hello works after compiling.
Because the name comes from the file, the file name must be a valid Java identifier. A file called hello-world.java contains a hyphen, so javac cannot derive a class name from it. Rename it to HelloWorld.java.
The generated class belongs to the unnamed package, and no other code can refer to it by name. So you cannot write new Hello() in another source file. The launcher can still create an instance, because it works from the class name you gave it.
How the launcher picks the entry point
Compiling a compact source file succeeds only if the implicit class has a launchable main method. If it has none, javac reports an error. The launcher uses the selection order from the earlier chapter on main method selection. It prefers a static main(String[] args), then a static main(), then an instance main(String[] args), and finally an instance main().
For an instance method, the launcher must construct the class first. The implicit class has a default no-argument constructor, so this works. If you add your own constructor, it must be accessible and take no parameters.
Passing command-line arguments
A main() with no parameters cannot see command-line arguments. To read them, declare the String[] parameter:
void main(String[] args) {
if (args.length == 0) {
IO.println("No arguments given.");
return;
}
for (String arg : args) {
IO.println("Argument: " + arg);
}
}In source-file mode, everything after the file name goes to the program, not to the launcher:
java Args.java alpha betaArgument: alpha
Argument: betaAfter compiling, the same arguments follow the class name: java Args alpha beta.
Options for the launcher itself must come before the file name. For example, java -Xmx256m Args.java alpha sets the heap size for the program, while java Args.java -Xmx256m passes the text -Xmx256m to your main.
Source mode versus compiled mode
The two routes give the same program behavior, but they differ in several practical ways.
| Aspect | `java Hello.java` | `javac Hello.java` then `java Hello` |
|---|---|---|
| Output on disk | None | `Hello.class` and any other generated classes |
| Compile step | Every run, in memory | Once, until the source changes |
| Startup cost | Includes compilation | Loading only |
| Compile errors | Printed, and the program does not start | Printed by `javac`, and no class file is written |
| Typical use | Experiments, scripts, teaching | Anything you keep, share, or package |
In source mode, java compiles the file each time, so a small edit and a re-run takes one command. The compilation cost is small for a short file. For a program you run often, compile once.
Warnings can also differ. Source mode reports compile errors, but it does not show you the whole javac option set. If you need -Xlint warnings, release targeting, or annotation processing, use javac directly. You can also pass compiler options in source mode, such as java --release 25 Hello.java, but javac gives you full control and clearer output.
Seeing what the compiler produced
Compile the file and inspect the result:
javac Hello.java
javap -p Hellofinal class Hello {
Hello();
void main();
}The class is final and has a default constructor, and main is an ordinary instance method. The output of javap may vary slightly between JDK builds, but the shape is the same. This confirms that the "script" is a normal class once compiled. The JVM does not know that the source was compact.
Several files in one run
A compact source file is often used alone, but source mode can also use other source files in the same directory. Suppose you have Main.java and Helper.java in one folder:
// Helper.java
class Helper {
static String shout(String s) {
return s.toUpperCase() + "!";
}
}// Main.java
void main() {
IO.println(Helper.shout("hello"));
}java Main.javaHELLO!The launcher finds Helper in Helper.java and compiles it in memory with Main.java. This works since Java 22. In older versions, source mode handled one file only.
For larger sets of files or dependencies on libraries, use a class path or a build tool. In source mode you can add -cp lib/* before the file name to make library JARs available.
Running a file as a script on Unix
Source mode also supports a "shebang" first line, so you can run a file like a shell script. The file must not end in .java, and the --source option is required in that case:
#!/usr/bin/java --source 25
void main() {
IO.println("Run me directly.");
}Save this as greet (no extension), mark it executable with chmod +x greet, and run ./greet. The --source 25 option tells the launcher to treat the file as Java 25 source. The shebang line is ignored by the compiler only when the launcher reads the file. A file with a shebang line cannot be compiled with javac.
Common errors
- "class found on application class path" or "no main method": The file has no launchable
main. Check that the method is notprivateand that the name and parameters are exactlymain()ormain(String[] args). - Using
staticincorrectly: A staticmainin a compact source file is allowed, but then it cannot call instance members without an object. Ifmaincalls a top-level method you wrote withoutstatic, removestaticfrommainor make the helper static too. - Running
java Hellobefore compiling: This fails with a class-not-found error, since noHello.classexists. Either compile first or runjava Hello.java. - Running
java Hello.javaafter editing a staleHello.class: Source mode ignores the old class file. It compiles from the source, so the result is always current. - Reading input with a mismatched mode:
IO.readlnreads from standard input in both modes. When you pipe input, as inecho Ada | java Hello.java, the program receives it the same way.
Summary of the workflow
- Write
Name.javacontaining top-level members and a launchablemain. - Run it with
java Name.javawhile you experiment. - Pass program arguments after the file name, and launcher options before it.
- Compile with
javac Name.javawhen you want a class file to keep, share, or inspect withjavap. - Run the compiled class with
java Name.
Exercise
You have a file Count.java containing void main(String[] args) { IO.println(args.length); }. What does java Count.java a b c print, and what does java -Xmx512m Count.java a b c print? Which command-line position would you use to give the program the argument -Xmx512m instead of configuring the JVM?
Show answer
Both commands print 3. In the second, -Xmx512m comes before the file name, so the launcher uses it to set the heap size, and the program still receives three arguments. To pass -Xmx512m to the program, put it after the file name, for example java Count.java a b c -Xmx512m, which prints 4.
Exercise
You run javac Hello.java, then change the greeting in Hello.java and run java Hello without recompiling. Which greeting appears, and why? What command would show the new greeting without a separate compile step?
Show answer
The old greeting appears, because java Hello loads the existing Hello.class, which was compiled from the earlier source. Running java Hello.java compiles the current source in memory and shows the new greeting.