Compiling & Running Java Programs
Every Java program goes through two steps before it produces output: compiling the source code into bytecode, and then running that bytecode on the JVM. This page walks through both steps from the command line, since understanding them makes it much easier to reason about what your IDE is doing behind a “Run” button.
Compiling a Single File
Suppose you have a file named HelloWorld.java:
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Compile it with the javac command:
javac HelloWorld.java
If there are no errors, javac produces a HelloWorld.class file in the same directory — this is the compiled bytecode.
Running the Compiled Program
To run the compiled program, use the java command:
java HelloWorld
Hello, World!
Compiling and Running Multiple Files
Real programs are made of several classes across multiple files. You can compile them all at once by passing multiple files (or a wildcard) to javac:
javac Main.java Helper.java # or, compile every .java file in the current directory javac *.java
Then run the program by naming the class that contains the main method you want to execute — usually your entry-point class:
java Main
The Classpath
The classpath is the list of locations — directories, .jar files, or both — where the JVM looks for compiled classes at run time. By default, java and javac look in the current directory, which is why the simple examples above “just work.” Once a project grows to depend on external libraries packaged as .jar files, you tell the JVM where to find them with the -cp (or -classpath) flag:
java -cp .:libs/some-library.jar Main # on Windows, classpath entries are separated by ; instead of : java -cp .;libs\some-library.jar Main
In practice, most real-world projects let a build tool like Maven or Gradle manage the classpath automatically, but it’s valuable to know what “ClassNotFoundException” and “NoClassDefFoundError” ultimately trace back to: the JVM looking in the classpath and not finding the class it needs.
Single-File Source-Code Execution
Since Java 11, the JDK supports running a single source file directly, without a separate compilation step:
java HelloWorld.java
Here the .java extension is required, since you’re pointing java at a source file rather than a compiled class name. Behind the scenes, the JVM compiles the file in memory and runs it immediately — nothing is written to disk. This is especially handy for quick scripts, small utilities, or trying out a snippet without the ceremony of a full project.
javac file.java — compiles source code into bytecode (.class files).
java ClassName — runs an already-compiled class (no file extension).
java file.java — compiles and runs a single source file in one step (Java 11+).