Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch single-file programs in Java 11 (or later)?

Tags:

java

java-11

JEP 330 describes a new feature in JDK 11 for launching single-file programs in Java. I've tried:

$ ./Example.java

but it doesn't work. What is the correct usage?

like image 567
Michael Easter Avatar asked Jan 28 '23 13:01

Michael Easter


2 Answers

Short-version:

$ java Example.java data.txt

or (with #!):

$ ./example data.txt

Details:

Working example here.

Consider a single-file program to print the lines in a file:

import java.nio.file.*;
import java.util.stream.Stream;

public class ExampleJDK11 {
    public static void main(String[] args) throws Exception {
        // snip ... print file args[0]
    }
}

Usage 1:

Assuming the code is in Example.java and that java is on the PATH, then usage is:

java Example.java data.txt

  • Note that there is no javac step (!)
  • Note that the filename need not match the classname.

Usage 2:

Assume the code is in a file, example, with a "shebang" line at the top:

#!/Users/measter/tools/jdk-11.jdk/Contents/Home/bin/java --source 8 

import java.nio.file.*;
import java.util.stream.Stream;
// as above

Usage is:

./example data.txt

like image 143
Michael Easter Avatar answered Jan 31 '23 08:01

Michael Easter


Though the answer by you includes correct information. Just trying to put this into simpler terms, a file can simply be executed using java from JDK11 onwards, for example on MacOS

.../jdk-11.jdk/Contents/Home/bin/java Sample.java

This would seek and execute the standard public static void main(String[] args) method. As one can notice(even beginners) that this method accepts args of type String, hence the arguments placed after the name of the source file in the original command line are passed to the compiled class when it is executed. Therefore the following command

.../jdk-11.jdk/Contents/Home/bin/java <file-name>.java arg1 arg2

would provide the string arguments arg1, arg2 during the execution phase.

Side note - If the file includes multiple classes with standard main methods, the first top-level class found in the source file which shall contain the declaration of the standard public static void main(String[]) method is executed.

like image 41
Naman Avatar answered Jan 31 '23 07:01

Naman