29

I wanted to check out some new features of java 11 which was released two days ago. JEP 330 states that I could launch a Java-Source-Code-Program without compiling. It should also support the usage of Shebang-Files.

Hence I have written this small Hello-World Program Test.java:

#!/opt/java/jdk-11/bin/java --source 11

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}

I downloaded JDK 11 and extracted it to /opt/java. Hence the Shebang itself is working. I.e. executing /opt/java/jdk-11/bin/java --version gives me

openjdk 11 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)

After making Test.java executable (using chmod +x Test.java) the execution is failing. I.e. ./Test.java gives me:

./Test.java:1: error: illegal character: '#'
#!/opt/java/jdk-11/bin/java --source 11
^
./Test.java:1: error: class, interface, or enum expected
#!/opt/java/jdk-11/bin/java --source 11
^
2 errors
error: compilation failed

As soon as I remove the Shebang-Line from Test.java and start it with /opt/java/jdk-11/bin/java --source 11 Test.java everything is working like a charm and I get the expected output: Hello World!

My machine is running Ubuntu 17.04. I have linked javac to the one from JDK 11 (i.e. executing javac -version gives javac 11).

1
  • Is this only an option with 1) OpenJDK 2) Unix flavour OS only... ie. does it work with Windows?
    – JGFMK
    Commented Sep 7, 2019 at 23:17

4 Answers 4

42

Remove the .java extension

The file name must not end with .java in order for the java executable to ignore the shebang line. You may use a different extension, but should preferably have no extension at all, as in the JEP example.

From JEP 330 (emphasis added):

When the launcher reads the source file, if the file is not a Java source file (i.e. it is not a file whose name ends with .java) and if the first line begins with #!, then the contents of that line up to but not including the first newline are ignored when determining the source code to be passed to the compiler. The content of the file that appears after the first line must consist of a valid CompilationUnit as defined by §7.3 in the edition of the Java Language Specification that is appropriate to the version of the platform given in the --source option, if present, or the version of the platform being used to run the program if the --source option is not present.

It doesn't need to end with ".sh" as mentioned in your self-answer; to avoid confusion, it probably shouldn't, because the file is not actually a shell script.

Rationale

Jonathan Gibbons, the author of the JEP, discussed the reasoning behind the requirement in a mailing list post. One of the biggest reasons is that they wanted to avoid making changes to the Java Language Specification to require all implementations to ignore a shebang line at the start of Java source files, which would have been a far more impactful change.

Some relevant excerpts from that message:

Shebang scripts are an executable format defined on some, but not all, platforms. Creating a shebang script is typically more than just adding an initial first line to a file; it typically involves a number of steps:

a. Add an initial shebang line to the file
b. Rename the file to a "command-friendly" name
c. Make the file executable
d. Install the file in some standard location

While renaming the file to a command-friendly name is optional, it is also expected to be common practice. For example, a source file named HelloWorld.java might be installed as helloworld. And, while the JEP describes use cases for executing a small single-file program with java HelloWorld.java or executing it as a platform-specific shebang script with just helloworld, it does not seem like there is a common use case to execute HelloWorld.java.

[...]

Since Java source files are different artifacts to platform-specific executable scripts, it makes sense to treat them differently, and since we do not want to change the Java language to support shebang lines, the suggestion is to amend the JEP and implementation so that shebang lines are never stripped from Java source files, i.e. files ending in .java. This avoids the problem of having the ecosystem of tools handling Java source files having to deal with arbitrary artifacts like shebang lines.

4
  • 6
    I think this is dumb. Why should it even concern itself with the filename to change its behavior? As far as I can tell, there is no disadvantage to ignoring the shebang even when the filename ends in .java. Commented May 13, 2021 at 17:19
  • @TrippKinetics It's because the shebang is a system-dependant non-portable feature. It completely breaks the write-once-run-anywhere principle so it was decided that it should not be included in the Java file format. I know it sounds stupid, but hey, it's 2024 and people are still confused about Java and JavaScript (see codereview.stackexchange.com/questions/tagged/java ). You really can't rely on people on matters like this.
    – Torben
    Commented May 3 at 11:28
  • 1
    That is only relevant in the situation where you're trying to exec the file on a platform which doesn't have shebang support. I don't think it is relevant to the behavior of the Java interpreter. I definitely don't think that the interpreter changing its behavior based on the filename is the Right Thing(tm). Commented May 10 at 17:42
  • 3
    @TrippKinetics While debating this requirement is off-topic for the comments here, I did track down statements from the JEP author explaining the reasoning for this and incorporated them into the answer.
    – Miles
    Commented May 11 at 2:25
9

A bit of trial and error gave me the correct solution. It was the file extension .java which causes those problems.

I.e. if I rename the file to Test.sh everything is working.

Here is a complete Hello-World-Shebang-Example:

Create a File Test.sh with content like

#!/opt/java/jdk-11/bin/java --source 11

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}

Make it executable (i.e. chmod +x Test.sh).

Last but not least execute it using ./Test.sh

1

According to the JEP you've linked to (see the shebang files section), the shebang file is to be used to launch the java process, not to be used as a parameter for java:

A shebang file to invoke the Java launcher using source-file mode must begin with something like:

#!/path/to/java --source version

For example, we could take the source code for a "Hello World" program, and put it in a file called hello, after an initial line of #!/path/to/java --source 10, and then mark the file as executable. Then, if the file is in the current directory, we could execute it with:

$ ./hello

In other words, what you want to do is rather make Test.java executable. You'd also have to rename it since it won't work as shebang and strip first line when it's named *.java.

$ move Test.java test
$ chmod +x test
$ ./test 

This will launch shebang processor which will strip first line and pass the rest of the script to /path/to/java and Java will compile the script and run the main method.

4
  • this does not work, the script filename should not have .java suffix
    – andrej
    Commented Sep 27, 2018 at 13:59
  • 1
    @andrej did you notice that it's being renamed in this answer?
    – ernest_k
    Commented Sep 27, 2018 at 14:01
  • @ernest-k nope. my bad. sorry. maybe you could mention this essential renaming
    – andrej
    Commented Sep 28, 2018 at 8:10
  • 1
    @ernest_k move is a Windows command. The UNIX equivalent is mv. Commented Jul 19, 2021 at 18:54
1

I don't understand the decision to require that it not end in java as any other language only requires that it be marked as executable.

However, you must have no file extension and your shabang line must either be the path to your java executable, or even better use (and this is the reason for my answer over other peoples)

note: you don't need java 21 for this shabang, that's just how you avoid the class to have just main (future versions may not need --enable-preview). #!/usr/bin/env -S java --source 11 will work with normal classes

#!/usr/bin/env -S java --source 21 --enable-preview
void main() {
  System.out.println("Hello, World!");
}

/usr/bin/env should always be used in this case because java does not have a standard location across all operating systems, and even if it did, quite frequently you might not want to use the OS one. I for example use ASDF, but I would never require anyone else do that.S

Although unrelated to this answer, if actually using sh you should always use #!/bin/sh because /usr is not guaranteed to be mounted early. Know if you're actually executing posix compliant scripts though (running on dash/ash), and whether you think anyone will want to use a non system installed interpreter (unlikely with shell itself). I'm just covering this part to help you understand the rational of when to use different shebang lines.

1
  • 1
    Great answer for the use of env -S! Commented Jun 6 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.