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!
In Java SE 11, you get the option to launch a single source code file directly, without intermediate compilation. This feature is particularly useful for someone new to the language who wants to try out simple programs; when you combine this feature with jshell , you get a great beginner's learning toolset.
You can't run Java program without JVM. JVM is responsible in running a Java program, but the only file that can be executed by JVM is Java bytecode, a compiled Java source code.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With