Execute Java File Without Compilation

From Java 11, Java provides flexibility to run Java code without compilation. It means we can execute Java code in a single step.

Before Java 11, if we execute Java file then first, we need to compile the code and then run the code. This whole process requires two major steps:

  • Compile Java code

  • Run Java code

To compile the code, we use javac java_file.java command. and

To run this file, we use java java_file command in the terminal (cmd in windows).

But if we are working with Java 11 then we don't need to follow these two steps. Just use single command java java_file.java and it will execute the file by producing the desired result.

Note: This feature is applicable if we have a single file of source code. It means all the code is in a single file, with no external dependency.

Time for an Example:

This is a simple Java example that we are taking to execute using Java 11 compiler.

public class Main {
	public static void main(String[] args){
		System.out.println("This code is executed without explicit compilation!");
	}
}


This code is executed without explicit compilation!

Exercise:

Try to run the above code using Java 8 with a single command (java java_file.java) and analyze the output.