Java 11 brings new feature which makes coding and experiments easy for developers.

Overview

Java is not a scripting language. For every program that we’d like to execute, we need to first compile it by explicitly running the javac command. This repetitive task makes developers in frustration to try out little snippets of code for testing purposes. Java 11 comes with a life-saving feature here.

We can now execute Java source code contained in a single file without the need to compile it first.

Executing a Java program with and without compilation
Executing a Java program with and without compilation

The new functionality is a great tool for beginners to the Java language and enables users to try ou logic in an easy way with less effort.

Let’s pick a simple example. The file HelloWorld.java renders the message “Hello World” on the console via System.out.println as part of the main method:

To execute, run the java command with Java 11. Java will compile the source file on the fly and run the program with the class file on the classpath. Any compilation error that might occur will be rendered on the console:

$ java -version java version “11.0.2” 2019-01-15 LTS OpenJDK Runtime Environment 18.9 (build 11.0.2+9-LTS) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode) $ java HelloWorld.java Hello World!
Limitations

Launching a single-file program without compilation is very convenient, but there are a couple of limitations that we need to be aware of.

With Java 11, the program cannot use any external dependencies other than the java.base module. For more info visit Modularity and Jigsaw Project. Furthermore, we can launch only a single-file program.

Calling methods from other Java source files is currently not supported, but we can define multiple classes in the same file if needed. We believe this feature is a helpful tool for rapid development and experimental features.

Leave a Reply

Your email address will not be published. Required fields are marked *