Scripting in Java :: Sep 28, 2017

Java is often ridiculed for its verbosity.

While less of a concern in large applications that require readability and structure, Java’s garrulity and compilation requirement has made it an uncommon choice for scripting. With the introduction of JShell, Java 9’s new REPL, the language can finally be leveraged from an interpreted context. Consider:

$ cat helloworld.jsh
println(“Hello world”)

$ jshell helloworld.jsh
Hello world

Note that /open PRINTING imports methods like print and printf without requiring the System.out prefix. By default, many classes in the standard library are automatically imported (try executing /imports in a console). The print statement does not require a semicolon, and the script ends with the /exit command.

Unfortunately, the depth of features in JShell severely hinders its startup performance. On my 2015 Macbook Pro, the above script takes over 7 seconds. Hopefully, features like Ahead of Time compilation or Class Data Sharing will improve speeds.

Alternatively, the Nashorn javascript engine included with the JDK can be used for scripting. Able to access nearly all of the Java standard library, Nashorn also executes faster, taking less than a second for hello-world:

$ cat jjs.js
print(“Hello world”);

$ jjs jjs.js
Hello world

In any case, great strides are being made in Java’s accessibility, and I look forward to further tooling development.