Command-Line
Compilation
Learn to compile and run Java programs from the terminal using javac and java: the foundational workflow every Java developer must know.
What Is Compilation?
Computers don't understand Java directly. A compiler translates your human-readable source code into a lower-level format the machine can execute. In Java, the compiler (javac) produces bytecode: a platform-independent instruction set stored in .class files.
The Two-Step Workflow
Why the Command Line?
IDEs like IntelliJ and Eclipse hide compilation behind buttons. But understanding the command-line workflow gives you deeper knowledge of what happens under the hood, and it's essential for server environments, build scripts, and the AP exam.
Anatomy of javac
Anatomy of java
javac vs java
| javac | java | |
|---|---|---|
| Purpose | Compiles source code | Runs bytecode |
| Input | FileName.java | ClassName |
| Output | .class file(s) | Program execution |
| Extension? | Yes: .java | No extension |
| Errors | Compile-time errors | Runtime exceptions |
Step-by-Step Workflow
Example 1: Hello World
Example 2: Multiple Files
When your project has multiple .java files, you can compile them all at once. Each file produces its own .class file, but you run only the class containing main.
Example 3: Packages
When your class declares a package, the directory structure must match the package name. You compile from the project root and specify the full path.
Understanding the Classpath
The classpath tells the JVM where to find .class files. By default it searches the current directory. You can set it explicitly with the -cp flag.
What Happens Inside?
The main Method
The JVM needs an entry point to begin execution. It looks for a method with this exact signature in the class you specify:
Common Mistakes
Quick Reference Table
| Task | Command | Example |
|---|---|---|
| Compile one file | javac File.java | javac Hello.java |
| Compile all files | javac *.java | javac *.java |
| Run a class | java ClassName | java Hello |
| Run with package | java pkg.Class | java com.myapp.App |
| Set output dir | javac -d dir File.java | javac -d build App.java |
| Set classpath | java -cp dir Class | java -cp build App |
Question 1 of 5
Which command compiles a Java source file named Calculator.java?
Question 2 of 5
After compiling Main.java successfully, which command runs the program?
Question 3 of 5
Your file is named myApp.java and contains public class MyApp. What happens when you run javac myApp.java?
Question 4 of 5
What does the -cp (or -classpath) flag do when used with the java command?
Question 5 of 5
Your class is in package com.school and the file is at com/school/App.java. Which pair of commands compiles and runs it correctly from the project root?