Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Java program without compiling

Tags:

java

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!
like image 943
satbekmyrza Avatar asked Feb 02 '19 12:02

satbekmyrza


People also ask

Can I run Java code without compiling?

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.

Can we run a Java program without JVM?

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.


1 Answers

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

like image 119
Fullstack Guy Avatar answered Sep 22 '22 02:09

Fullstack Guy