Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
No this isn’t about JavaScript. This is a new feature introduced in Java 11, opening the possibility of using Java as a scripting language. The definition of Scripting can be somewhat a woolly one, but normally scripting languages tend to be associated with the use of an interpreter to allow them to execute the source code at runtime. Java is a compiled language, so the source must be passed through a compiler first to produce executable byte code. This byte code is then executed by the Java Virtual machine. Given this process, compiled languages aren’t really used for scripting. Java 11 tries to change this.
Before we look at scripting, it’s important to understand this change that opens the doorway. Java 11 allows a single class with a main method to be executed directly from the command line without the need to compile it first (i.e. no need to run the source through javac). Under the hood it will be compiled, but it removes the need to explicitly call javac. It only works for a single class.
public class SayHello() {
public static void main( String... args ) {
System.out.println( "Hello, without javac!" );
}
}
Traditionally, to compile and run the above code would require two commands;
# Pre Java 11
# Compile it
javac SayHello.java
# Run it
java SayHello
With Java 11 and beyond, a single class can be executed like this…
# Compile on the fly and run a single class file with one command
java SayHello
This now opens the possibility for writing scripts in Java. For scripting, using the above approach, you can create a source file with any file name (no need to match the class name for this one) and even omit the .java file extension.
There is no requirement to execute java (passing the class name), now we can run the script directly simply by adding a shebang line at the top of the source file…
#!/usr/bin/java
public class SayHello() {
public static void main( String... args ) {
System.out.println( "Hello, without javac!" );
}
}
To run this, simply call the script, as you would a bash script. Java is compiling this for you, but no .class files are produced as a result.
./sayhello
Personally speaking, I can see the benefits to those who want to write script but only know Java or prefer to use it, maybe Developers in a DevOps setting, For me I would probably favour Python for simple scripting, but this does provide another option. Most likely comes down to available technology stack and maybe personal choice to use what you are most comfortable with.
Incase you confuse Java with JavaScript, here a nice quote I came across recently.
Java is to JavaScript as Car is to Carpet