Difference between running Java from command line with file ending and without

mrbela :

I just wrote a simple hello world class called Hello:

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

The "normal" way to run it from the command line as far as I know is

1) compiling it (and creating the file Hello.class):

javac Hello.java

2) running it:

java Hello

I just found out by accident that it is also possible to just invoke

java Hello.java

without creating a Hello.class file first! This also does not crate an own class file..

So now, I am asking myself, what exactly happens, when I just run java Hello.java?

Basil Bourque :

tl;dr

See JEP 330 describing this new feature in OpenJDK 11 and later, where java MyClass.java will both compile and run a single-file of source code.

Java 11

You have found a new feature in Java 11 implementations built on OpenJDK 11. For convenience, a single .java file can now be compiled and executed merely by calling java on the command line.

The java automatically calls on javac to do the compiling. The resulting compiled class is then run.

See JEP 330: Launch Single-File Source-Code Programs. To quote that JEP:

Single-file programs -- where the whole program fits in a single source file -- are common in the early stages of learning Java, and when writing small utility programs. In this context, it is pure ceremony to have to compile the program before running it. In addition, a single source file may compile to multiple class files, which adds packaging overhead to the simple goal of "run this program". It is desirable to be able to run the program directly from source with the java launcher:

java HelloWorld.java

And, yes, this simple feature should have been built decades ago to help countless beginners trying to learn Java.


Caveat: A Java implementation not built from the OpenJDK source-code may or may not include such a feature. That is the difference between a JEP (OpenJDK only) and a JSR (defined in Java specifications).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132892&siteId=1