javac and java
- Java course
- Beginner
- Lesson 5/116
- 4 min
Learn to compile and run from the command line.
What is javac?
javac is the Java compiler. It turns your source file (.java) into a .class file containing bytecode that the JVM can read.
javac Main.javaWhen the command runs, Main.class appears in the same folder. If compilation fails, you get error messages; on success it finishes silently.
javac checks the source code: it catches syntax errors, type mismatches and missing semicolons.
What does the java command do?
The java command runs a compiled .class file on the JVM. You pass the class name without extension:
java MainThis command loads Main.class, finds the main method and runs it. The output appears on the screen.
This two-step flow follows the compile once, run anywhere philosophy. The same .class file runs on Windows, Linux and macOS.
Practice Write a compilable program
Define a Main class with a main method. Print Running with println. This code must compile with javac Main.java and run with java Main.
Sample solution
public class Main {
public static void main(String[] args) {
System.out.println("Running");
}
}Expected output
Running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What turns a .java file into .class?
- java
- javadoc
- jar
- javac Correct answer
Explanation: javac is the Java compiler.
2 Complete the compile command
____ Main.java
javac Main.java
Explanation: javac Main.java compiles the file.
3 Match the compile stages
| Term | Meaning |
|---|---|
javac |
Compiles |
.class |
Bytecode |
java |
Runs |
JVM |
Runtime |