17

Recently, I installed Java 11. When coding, accidentally, instead of compiling Main.java with javac Main.java, I wrote java Main.java. It did not show me any errors and worked out without any issues. Why did this happen? Is this a new feature in newer versions of Java?

Contents of Main.java:

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

Running in Java 8:

java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)

>>> java Main.java
Error: Could not find or load main class Main.java

Running in Java 11:

java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

>>> java Main.java
Hello, World!
sat63k
  • 333
  • 1
  • 2
  • 13
  • 8
    Yes, Java 11 introduced the ability to execute single-file programs using the source file. Check this: [How to launch single-file programs in Java 11 (or later)?](https://stackoverflow.com/questions/51935636/how-to-launch-single-file-programs-in-java-11-or-later) – ernest_k Feb 02 '19 at 12:28

1 Answers1

19

This feature was introduced as a part of JEP 330: Launch Single-File Source-Code Programs.

In source-file mode, the effect is as if the source file is compiled into memory, and the first class found in the source file is executed. For example, if a file called HelloWorld.java contains a class called hello.World, then the command

java HelloWorld.java is informally equivalent to

javac -d HelloWorld.java java -cp hello.World

This is the JEP

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44