Skip to main content

Java scripts

Single-file

Turns out that starting with Java 11 you can run single-file Java programs without compiling them first (JEP 330). So if you have a file Factorial.java with these contents:

public class Factorial {
  public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    System.out.println(factorial(n));
  }

  public static long factorial(int n) {
    return n == 0 ? 1 : n * factorial(n - 1);
  }
}

You can run it like:

java Factorial.java 5

Multi-file

And starting with Java 22 you can also run multi-file Java programs without compiling them (JEP 458). Say you have a file Factorial.java with these contents:

public class Factorial {
  public static long factorial(int n) {
    return n == 0 ? 1 : n * factorial(n - 1);
  }
}

And a Prog.java file with these contents

public class Prog {
  public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    System.out.println(Factorial.factorial(n));
  }
}

You can run it like:

java Prog.java 5

Shebang files

You can add a shebang line to single-file programs! Rename the above file to factorial (without .java), mark it as executable, and add this shebang line:

1#!/usr/bin/env java --source 21
2public class Factorial {
3  // ...
4}

Now you can run it like:

./factorial 5

Created