Before the java11 version, If you want to compile and run a single java file, You have to follow two steps (javac and java command) steps.
- First, write a java program code as given below i.e HelloWorld.java
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World Example");
}
}
- Once you have written the code, Next, compile the program using the javac command.
javac HelloWorld.java
It generates the HelloWorld.class file in the current directory.
- Next, Run the
java HelloWorld
program to execute the program.
java HelloWorld
Output:
Hello World Example
If you modified the code and run it without compiling the java file, It prints old code.
Java11 simplified using a one-step process by skipping the compilation step.
You can directly run java HelloWorld.java without using the javac command.
java HelloWorld.java
With this command, It compiles the code and loads it into memory in JVM, and runs the program.
If there are any errors in the source code, It throws compilation errors.
Another point to note is Before java11, FileName and class name should be the same.
With java11, you can compile files with different file names.
let’s create an example.java file
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World Example");
}
}
Now, with java11, you can run and compile with the java example.java
command.
If you try to compile with javac example.java, It throws a compilation error.
Running in Java files with shebang files
java11 simplified by adding shebang files and running as executable files.
For example, Let’s create a hello.java which contains the following things.
- The first line is the
shebang
line that starts with java path and--source
option, with version11
.
#!/usr/bin/java --source 11
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World Example");
}
}
Now, run using the below steps in Unix and macOS.
The file name can be renamed without the .java extension. changed hello.java to hello.
The file should give executable permission by running the below command.
chmod +x hello
Next, run the file as the executable file in Linux and Unix.
./hello
With java 11, It improves developer productivity by improving single file execution steps.
You can check more about JEP 330 : Launch Single-File Source-Code Programs