JAVA • GETTING STARTED AND TOOLING

Command-Line Compilation — Compile and run a Java program from the command line (javac / java)

Learn to transform your Java source code into a running program using just a terminal window.

Historical Context & Motivation

Before fancy code editors and IDEs like IntelliJ or Eclipse existed, every programmer compiled and ran their code from a command line — a simple text-based interface where you type instructions directly to the operating system. When James Gosling and his team at Sun Microsystems created Java in the mid-1990s, the command-line tools javac and java were the very first way anyone ever compiled and ran a Java program. Understanding these tools gives you direct control over the compilation process and helps you grasp what IDEs do behind the scenes.

1991
Project Green Begins
James Gosling at Sun Microsystems starts developing a new language originally called "Oak," intended for interactive television devices.
1995
Java 1.0 Released
Java is publicly released with the JDK (Java Development Kit), which includes the javac compiler and java runtime launcher. The motto is "Write Once, Run Anywhere."
2006
Java Goes Open Source
Sun Microsystems releases Java as open-source software under the GPL license, leading to the OpenJDK project that continues today.
2017–Now
Modern JDK Releases
Oracle adopts a six-month release cadence. The javac and java commands remain the fundamental tools in every JDK distribution, even as IDEs have become popular.

Even today, every IDE you might use — IntelliJ IDEA, Eclipse, or VS Code with extensions — ultimately calls javac and java under the hood. So the question is: how exactly do you turn a plain .java text file into a running program using just these two commands?

Core Principles & Definitions

Java uses a two-step process to go from the code you write to a running application. First, your human-readable source code is compiled into an intermediate form. Then, that intermediate form is executed by the Java Virtual Machine. This design is what makes Java portable across different operating systems.

1

Source Code (.java)

The plain-text file you write in Java. It must have the .java extension, and the filename must match the public class name inside the file.
2

Bytecode (.class)

The intermediate, platform-independent instructions produced by javac. Bytecode is not human-readable — it is designed for the JVM to interpret.
3

javac (Compiler)

The Java compiler. It reads your .java file, checks for syntax errors, and produces a .class file containing bytecode.
4

java (Launcher)

The Java application launcher. It starts the JVM, loads your .class file, and begins executing the main method.
5

JVM (Java Virtual Machine)

The runtime engine that interprets bytecode and translates it into native machine instructions for your specific OS and hardware. This is what makes Java platform-independent.
✦ KEY TAKEAWAY
Think of the Java compilation process like translating and performing a play. Your .java file is the script written in English. The javac compiler is like a translator who converts the script into a universal stage notation (bytecode) that any theater company in the world can read. The java launcher is the director who reads that notation and makes the actors (your CPU) perform the show.

Visual Explanation — The Compilation Pipeline

The pipeline flows from left to right: your source code is fed into javac, which produces bytecode. The java launcher then loads that bytecode into the JVM and produces your program's output. The terminal commands at the bottom show the exact keystrokes you type.

Notice in the diagram that there are two distinct phases. The compilation phase (using javac) is where errors in your syntax — like a missing semicolon or a misspelled keyword — are caught. If javac finds any errors, it will print them to the terminal and refuse to create the .class file. Only when compilation succeeds can you move to the execution phase (using java), where the JVM actually runs your program.

How It Works — Step by Step

Writing the Source File

Every Java program begins as a plain text file saved with the .java extension. A critical rule is that the filename must exactly match the public class name declared inside the file, including capitalization. For example, if your class is called HelloWorld, the file must be named HelloWorld.java. You can create this file in any text editor — Notepad, VS Code, nano, or vim.

⚠️ Common Mistake
If you name your file helloworld.java (lowercase) but the class inside is public class HelloWorld, the compiler will throw an error. Java is case-sensitive — capitalization matters everywhere.

Compiling with javac

Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux), navigate to the folder containing your .java file using the cd command, and type:

COMPILE COMMAND
javac HelloWorld.java
javac = the Java compiler program; HelloWorld.java = the source file to compile. If successful, a file called HelloWorld.class appears in the same directory. If there are errors, they are printed with line numbers.

Running with java

Once compilation succeeds, you execute the program by typing:

RUN COMMAND
java HelloWorld
java = the JVM launcher; HelloWorld = the class name (NOT the filename — no .class extension). The JVM finds the public static void main(String[] args) method and begins execution there.
💡 Important
When running with java, you provide the class name, not the file name. Writing java HelloWorld.class is a very common beginner error and will produce an error message about not finding the class.

Understanding Compiler Errors & the Classpath

One of the biggest advantages of command-line compilation is that you see error messages directly in the terminal. Learning to read these messages is a crucial skill. The compiler tells you the file name, the line number, and a description of what went wrong. Let's look at the anatomy of a typical error and the concept of the classpath.

This diagram breaks down a typical javac error into its parts: the file name, line number, error type, description, and the caret pointer showing exactly where the problem is.

The Classpath

The classpath tells the JVM where to look for .class files. By default, it looks in the current directory. If your class files are somewhere else, you can specify the classpath using the -cp flag. For example, java -cp /myproject/bin HelloWorld tells Java to look inside the /myproject/bin folder for the compiled class. For now, keeping your terminal in the same folder as your files is the simplest approach.

Worked Example — Hello World from Scratch

Let's walk through the complete process of writing, compiling, and running a Java program from the command line. We will create a program that prints a greeting message.

Compiling and Running HelloWorld
1
Step 1 — Create the Source FileOpen any text editor and type the following code. Save the file as HelloWorld.java in a folder you can easily navigate to (for example, C:\JavaProjects on Windows or ~/JavaProjects on macOS/Linux).
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2
Step 2 — Open the Terminal and NavigateOpen your terminal application. Use the cd (change directory) command to navigate to the folder where you saved the file.
cd ~/JavaProjects (macOS/Linux) or cd C:\JavaProjects (Windows)
3
Step 3 — Verify the JDK is InstalledType javac -version to confirm that the Java Development Kit is installed and available on your system PATH. You should see output like javac 17.0.2. If you get a "command not found" error, you need to install the JDK and add it to your system's PATH environment variable.
javac -version → javac 17.0.2
4
Step 4 — Compile the ProgramRun the compiler by typing javac HelloWorld.java. If the code has no errors, the terminal will simply return to the prompt with no output — silence is success! A new file called HelloWorld.class will appear in the same directory. You can verify by typing ls (macOS/Linux) or dir (Windows).
javac HelloWorld.java → No output (success). HelloWorld.class created.
5
Step 5 — Run the ProgramExecute the compiled bytecode with java HelloWorld. Note: do NOT include the .class extension. The JVM locates the main method and starts executing it.
java HelloWorld → Hello, World!
🔄 Pro Tip
After changing your source code, you must recompile before running again. If you only run java HelloWorld without recompiling, you will still see the old program's behavior because the .class file hasn't changed.

Command Line vs. IDE — Strengths & Limitations

You might wonder: if IDEs exist and make life easier, why bother with the command line? The truth is that both approaches have real value. Understanding the CLI gives you foundational knowledge that pays off when debugging IDE issues, working on servers, or automating builds. Meanwhile, IDEs dramatically speed up everyday development work.

Comparing command-line and IDE workflows for Java development
FeatureCommand Line (javac / java)IDE (IntelliJ, Eclipse, etc.)
SetupJust install the JDK — nothing else neededInstall JDK plus the IDE application
Error FeedbackErrors shown after you compileErrors highlighted in real-time as you type
Speed for Small ProgramsVery fast — no project setup requiredRequires creating a project first
Large ProjectsGets tedious managing many files manuallyExcellent — auto-manages dependencies and builds
Learning ValueHigh — you see exactly what happens at each stepLower — the process is hidden behind buttons
Server / Remote UseEssential — servers rarely have graphical interfacesNot available on remote servers without GUI
✦ KEY TAKEAWAY
Think of the command line as learning to drive a manual transmission car. It takes a bit more effort, but you truly understand how the engine, clutch, and gears work together. An IDE is like driving an automatic — smoother and faster in daily life, but you might not understand what's happening under the hood. The best developers are comfortable with both.

Connection to Build Tools & Advanced Workflows

As your projects grow beyond a handful of files, manually running javac on each file becomes impractical. This is where build tools come in. Tools like Maven and Gradle automate the compilation, testing, and packaging of Java projects. But at their core, these tools are calling javac and java for you — just in a smarter, more organized way.

How basic CLI skills scale into professional Java workflows
ConceptWhat You Know NowWhat Comes Next
CompilationRun javac manually on each fileBuild tools compile all files automatically based on a config file
DependenciesSet the classpath manually with -cpMaven/Gradle download and manage library dependencies for you
PackagingIndividual .class filesBundle into .jar (Java Archive) files for easy distribution
TestingTest by running the program and checking output visuallyAutomated testing frameworks like JUnit run thousands of tests in seconds

Starting with JDK 11, Java also supports single-file source-code launching. You can skip the explicit compile step and run java HelloWorld.java (note the .java extension), and the JVM will compile and run the file in one step. This is handy for quick experiments, but for multi-file projects, the traditional two-step process remains essential. As you advance in your Java journey, the command-line fundamentals you learn today will make every new tool easier to understand.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words why Java uses a two-step process (javac then java) instead of directly running the source code like some other languages do. What advantage does the intermediate bytecode provide?
PROBLEM 2 — BASIC CALCULATION
You have a file called Greeting.java containing a class called public class Greeting with a valid main method. Write the exact two terminal commands needed to compile and run this program.
PROBLEM 3 — INTERMEDIATE
A student writes the following code and saves it as MyApp.java: public class myApp { public static void main(String[] args) { System.out.println("It works!") } } Identify all the errors that javac would report and explain how to fix each one.
PROBLEM 4 — APPLIED
You are working on a remote Linux server that has no graphical interface — only a terminal. You need to write a Java program that prints the current date. Describe the complete sequence of actions, from creating the file to seeing the output. Assume the JDK is installed. Your program should use java.time.LocalDate.now().
PROBLEM 5 — CRITICAL THINKING
A student compiles their program successfully and gets a .class file. However, when they run java Calculator, they get: Error: Main method not found in class Calculator. The code compiles without any warnings. What could cause this runtime error despite successful compilation, and what are at least two possible fixes?

Lesson Summary

Java programs are built through a two-step process. First, you use the javac compiler to convert your human-readable .java source file into platform-independent bytecode (.class file). Then, you use the java launcher to start the JVM (Java Virtual Machine), which interprets the bytecode and runs your program. The filename must match the public class name, you include the .java extension when compiling but omit the .class extension when running.

Mastering command-line compilation gives you a transparent view of how Java works under the hood — knowledge that transfers to understanding IDEs, build tools like Maven and Gradle, and real-world server deployments. Remember: reading compiler error messages carefully (file, line number, description, caret) is one of the most valuable debugging skills you can develop.

Varsity Tutors • Java • Command-Line Compilation — Compile and run a Java program from the command line (javac / java)