Compiling and Running Java
How javac and java turn source code into bytecode and then into a running program.
2 min read
Java's two-step build process — compile, then run — trips up a lot of newcomers coming from languages with a single run command. Understanding what each step actually does removes most of that confusion.
Step 1: javac compiles source to bytecode
javac (the Java compiler) takes your .java source file and turns it into a .class file containing bytecode — a compact, platform-independent instruction format that the JVM understands. This is a real compilation step: syntax errors, type mismatches, and missing semicolons are all caught here, before anything runs.
javac Hello.java
# produces Hello.class in the same directoryBytecode is not machine code — you can't run a .class file directly on your CPU. It's an intermediate format, which is exactly what makes it portable: the same Hello.class file runs unmodified on any machine with a JVM.
Step 2: java runs the bytecode
The java command launches the JVM, loads the compiled class, and calls its main method.
java Hello
# Hello, World!Note there's no .class extension in that command — you name the class, not the file. The JVM interprets the bytecode instruction by instruction, but for code that runs repeatedly (loops, hot methods), the JIT (just-in-time) compiler kicks in and compiles those sections to native machine code on the fly, which is a big part of why long-running Java programs get faster the longer they run.
Compiling and running multiple files
Real programs span multiple .java files. javac handles a whole directory at once:
javac *.java
java MainClassOnce a project grows beyond a handful of files, hand-running javac/java gets impractical — that's what build tools like Maven and Gradle are for. They manage compiling, dependency downloads, testing, and packaging into a single command (mvn compile, gradle build), and virtually every real-world Java project uses one of them rather than calling javac directly. You'll still see the raw compile/run cycle constantly in tutorials and quick experiments, though, so it's worth understanding what's happening underneath.
Packaging: the JAR file
For distribution, compiled classes are typically bundled into a JAR (Java Archive) — essentially a zip file of .class files plus metadata about which class contains main.
jar cfe Hello.jar Hello Hello.class
java -jar Hello.jarThat's the same Hello.class from before, just packaged so it can be shipped and run as a single file instead of a loose folder of .class files.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.