Run a Java program directly from source code file
- Details
- Written by Nam Ha Minh
- Last Updated on 21 April 2020   |   Print Email
Perhaps you’re very familiar with the traditional way of compiling and running Java program in command line as follows:
javac Hello.java
java Hello
This involves in 2 steps: compile the .java file to the byte code .class file, and run the compiled .class file. It is somewhat verbose and “ceremony” for small, utility programs that are contained in a single source code file.
So from JDK 11, there’s a simpler way which you can use to run a Java program directly from its source file, like this:
java Hello.java
This feature is called Launch Single-File Source-Code Programs available in JDK since Java 14. Use the same command if the source file has package statement.
Under the hood, the Java compiler is invoked to compile the source file in memory, and then the Java Virtual Machine executes the compiled code. That means the process is the same as in previous JDK versions – It’s not interpreted.
Of course you can pass arguments to the program as normal. For example:
java Sum.java 10 38 29
And pass JVM arguments as normal. For example:
java –cp mysql-connector-java.jar Database.java
Note that this feature only applies for a program contained in a single source code file and no .class files generated. I think it will make learning Java programming more easily and more convenient for running small, utility programs.
Watch the video:
Other Java Tools Tutorials:
- java command examples
- javac command examples
- jar command examples
- Java serialver command examples
- Understanding the triad tools javac, java and jar in JDK
- The Java Shell (jshell) Tutorial
- How to compile, package and run a Java program using command-line tools (javac, jar and java)
Comments