How to write single file source code executable in java

Since JDK 11, Java supports executing source file directly without the need to first compile to class file, which makes it possible to write scripting in Java, as is usually done with dynamic programming languages like python, ruby, or nodejs. This post serves as an example as well as a quick reference on how to achieve it.

The steps can be simply summarized as follows

  • Ensure shebang is set like: #!/usr/bin/env java --source 17, note the --source is important

  • Ensure the first top-level class in the source code file contains the psvm method as the execution entrance

  • Ensure file name does not have .java extension and file is executable with chmod +x ./filename

Example

  • Save below as file named fib and make it executable
#!/usr/bin/env java --source 17

public class Fib {

  public static void main(String[] args) {
    long num = Long.parseLong(args[0]);
    System.out.println(fib(num));
  }

  private static long fib(long n) {
    if (n < 2) return n;

    return fib(n - 2) + fib(n - 1);
  }
}
  • Try from command line
~$ ./fib 10
55

Notes

  • It can also be run without setting shebang line #!/usr/bin/env java --source 17 in ways of java filename.java, in which case the file doesn’t need be set executable and the filename doesn’t need match the first top-level class name in source code file (like regular java code), but the .java file extension is required.

  • If the single-file executable uses external dependency outside JDK, it can be passed with the usual -cp parameter like: java -cp /path/to/3rd-party.jar filename.java.

References

java