Do you know Java: Single Source File Code


Java 11 introduced a new way of executing applications. That gives us the opportunity to do it without excplicitely compiling it. What’s more, Java code can be run as a script.

In Java, compilation and execution of an app are two different steps. The java command gives us the feeling that we work with an interpreter.

The Pre-Java-11 era

Compilation of the source code and execution of the app are separated commands before Java 11, as we see here:

$ javac Hello.java
$ java Hello
Hello World!

The Java 11 era

Java 11 compiles the code and then executes it in one step, though it does not generate .class file.

$ java Hello.java
Hello World!

Java is strongly engaged to backward compatibility, hence, to use this one-step approach with other versions as well, we can use --source option to specify which version we are inteded to use.

$ java Hello.java --source 9
Hello World!

Good old jars are used in the same way as they have been used previously:

$ java -cp guava-28.0-jre.jar HelloList.java

Shebang

Shell scripts start with a commented line at the beginning of the file, in general. This commented line holds information to the executor about interpreter and its location. It can be bash, python, ruby, perl, you can name it.

Java also can provide this functionality to execute applications.

#!/bin/java --source 11

class Shebang {
    public static void main(String[] args) {
        System.out.println("Shebangs! Shebangs!");
        System.out.println("Num of arguments: " + args.length);
    }
}

I have to mention the followings:

  • the source file has to be executable. To achieve this, execute chmod +x Shebang or chmod 744 Shebang,
  • extension has to be nothing, .sh or some other, .exe is also good choice but not .java,
  • --source option is mandatory here, otherwise ClassNotFoundException exception is raised,
  • with this option we can define which Java version we are intended to use.

Java 11 has brought a lot of funny features like java command can compile and execute the source file in one step. Source code is executable when shebang is on the top.

Code can be found: https://github.com/torokmark/do-you-know-java