Saturday, December 29, 2018

Java 11: Running single-file programs and "shebang" scripts

In Java 11, the java launcher has been enhanced to run single-file source code programs directly, without having to compile them first.

For example, consider the following class that simply adds its arguments:

import java.util.*;
public class Add {
  public static void main(String[] args) {
    System.out.println(Arrays.stream(args)
      .mapToInt(Integer::parseInt)
      .sum());
  }
}

In previous versions of Java, you would first have to compile the source file and then run it as follows:

$ javac Add.java
$ java Add 1 2 3
6

In Java 11, there is no need to compile the file! You can run it directly as follows:

$ java Add.java 1 2 3
6

It's not even necessary to have the ".java" extension on your file. You can call the file whatever you like but, if the file does not have the ".java" extension, you need to specify the --source option in order to tell the java launcher to use source-file mode. In the example below, I have renamed my file to MyJava.code and run it with --source 11:

$ java --source 11 MyJava.code 1 2 3
6

It gets even better! It is also possible to run a Java program directly on Unix-based systems using the shebang (#!) mechanism.

For example, you can take the code from Add.java and put it in a file called add, with the shebang at the start of the file, as shown below:

#!/path/to/java --source 11
import java.util.*;
public class Add {
  public static void main(String[] args) {
    System.out.println(Arrays.stream(args)
      .mapToInt(Integer::parseInt)
      .sum());
  }
}

Mark the file as executable using chmod and run it as follows:

$ chmod +x add
$ ./add 1 2 3
6

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.