Core Java

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
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 11: Running single-file programs and “shebang” scripts

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
chaitra
5 years ago

Hey thanks for sharing the valuable information. it is really helpful for us, I need some help for my Website

Back to top button