How to Compile and Run Java Programs from the Command Line
Learn exactly what javac and java do, why the file name must match the public class, how to run single and multi-file programs without compiling first, and how to read and fix the most common command-line errors.
kvi5hnuCode Sprout team member12 min readOn this page
Most of the time you'll write Java in an IDE that compiles and runs your code at the click of a button. Even so, every Java developer should be able to compile and run a program by hand in a terminal, for three reasons:
- Troubleshooting. When you first install Java, the terminal is the quickest way to check that everything works before adding an IDE on top.
- Understanding. Doing the steps yourself shows you what the IDE does behind your back. When the IDE reports a strange error, you'll know what's really going on.
- Real-world use. Build servers, Docker containers, deployment scripts and production servers run Java from the command line.
This article assumes you've installed a JDK and that javac --version works (see the previous article).
Your First Program, Step by Step
1. Create a folder and a source file
Make a folder for your experiments, for example hello-java, and create a file named exactly Welcome.java in it, with a capital W. Use any plain-text editor (VS Code, Notepad++, Sublime Text, nano, vim). Don't use a word processor such as Word, which adds formatting.
/**
* Prints a greeting followed by an underline of the same length.
*/
public class Welcome {
public static void main(String[] args) {
String greeting = "Welcome to Core Java!";
System.out.println(greeting);
for (int i = 0; i < greeting.length(); i++) {
System.out.print("=");
}
System.out.println();
}
}
You don't need to understand every line yet; the next part of the course takes this program apart piece by piece. In short: it stores a greeting in a variable, prints it, then prints one = per character of the greeting, so the underline has exactly the same length.
2. Open a terminal in that folder
- Windows: in File Explorer, open the folder, click the address bar, type
cmd(orpowershell) and press Enter. - macOS: right-click the folder in Finder → New Terminal at Folder (or open Terminal and
cdto it). - Linux: right-click in the file manager → Open in Terminal, or
cdto it.
Check that the file is there with dir (Windows) or ls (macOS/Linux).
3. Compile with javac
javac Welcome.java
If nothing is printed, that's good news: javac only speaks up when something is wrong. List the folder again and you'll see a new file, Welcome.class, containing the bytecode for the Welcome class.
4. Run with java
java Welcome
Welcome to Core Java!
=====================
Congratulations, you've compiled and run a Java program by hand.
What just happened?
| Command | Program | What it does | Input | Output |
|---|---|---|---|---|
javac Welcome.java | The Java compiler | Checks the source for errors and translates it into bytecode | a file name, with .java | Welcome.class |
java Welcome | The Java launcher | Starts a JVM, loads the class Welcome, and calls its main method | a class name, with no extension | your program's output |

The single most common beginner mistake comes from mixing these up: javac takes a file name; java takes a class name.
The Rules That Trip Everyone Up
Rule 1: Java is case-sensitive
Welcome, welcome and WELCOME are three different names. The class is called Welcome, so the file must be Welcome.java and the run command must be java Welcome.
Watch what happens with a lowercase w:
$ java welcome
Error: Could not find or load main class welcome
Caused by: java.lang.NoClassDefFoundError: welcome (wrong name: Welcome)
On Windows and macOS, whose file systems ignore case by default, the JVM finds the file Welcome.class when you ask for welcome. It then notices that the class inside is really named Welcome and refuses to run it ("wrong name"). On Linux you'd simply get "Could not find or load main class welcome" with a ClassNotFoundException.
Fix: type the class name with exactly the same capitalisation as in the source code.
Rule 2: A public class must live in a file with the same name
If a class is declared public, its source file must be named after it, plus .java. Save the program above as Hello.java and the compiler refuses:
$ javac Hello.java
Hello.java:4: error: class Welcome is public, should be declared in a file named Welcome.java
public class Welcome {
^
1 error
Fix: rename the file to Welcome.java, or rename the class to match the file.
Rule 3: Don't add extensions when running
$ java Welcome.class
Error: Could not find or load main class Welcome.class
Caused by: java.lang.ClassNotFoundException: Welcome.class
The launcher reads Welcome.class as "a class named class in a package named Welcome" (dots separate package names, as you'll learn later), and no such class exists. Fix: java Welcome.
And the reverse:
$ javac Welcome
error: Class names, 'Welcome', are only accepted if annotation processing is explicitly requested
1 error
javac needs the file name. Fix: javac Welcome.java.
Rule 4: Make sure the file really has a .java extension
On Windows, Notepad likes to save files as Welcome.java.txt, and File Explorer, which hides "known" extensions by default, shows it as Welcome.java. javac then reports:
error: file not found: Welcome.java
Fixes:
- Run
dirin the terminal: it shows real file names, including.txt. - In Notepad's Save As dialog, put the name in quotes:
"Welcome.java", or set Save as type to All files. - Better: turn on File name extensions in File Explorer (View → Show → File name extensions), and use a programmer's editor.
On Linux and macOS, also check that the capitalisation of the file name matches (welcome.java isn't Welcome.java).
Rule 5: "command not found" means PATH, not your code
'javac' is not recognized as an internal or external command,
operable program or batch file.
or javac: command not found. This has nothing to do with your program: the terminal can't find the compiler. Revisit the PATH section of the installation article and open a new terminal.
Reading Compiler Errors
When your code has a mistake, javac prints the file, the line number, a description, the offending line, and a caret ^ pointing at the spot. Here are the two errors you'll see most often.
Misspelled name. Java is case-sensitive, so string isn't String:
Welcome.java:6: error: cannot find symbol
string greeting = "Welcome to Core Java!";
^
symbol: class string
location: class Welcome
1 error
"Cannot find symbol" means "you used a name I don't know". Check the spelling and capitalisation, and check that the variable or method was declared.
Missing semicolon:
Welcome.java:7: error: ';' expected
System.out.println(greeting)
^
1 error
The caret points to where the compiler expected the semicolon, at the end of the statement.
Running Without Compiling First: Source-File Mode
Since Java 11, the java launcher can run a source file directly. It compiles the code in memory and runs it, without writing a .class file:
java Welcome.java
Welcome to Core Java!
=====================
Notice the difference from Rule 3: java Welcome.class is an error, but java Welcome.java is a valid request to launch a source file.
Since Java 22, source-file mode also works for programs spread over several files in the same folder. Suppose you have:
public class Greeter {
public static void main(String[] args) {
System.out.println(Messages.hello(args.length > 0 ? args[0] : "world"));
}
}
class Messages {
static String hello(String name) {
return "Hello, " + name + "!";
}
}
java Greeter.java Ada finds Messages.java automatically, compiles both, and prints Hello, Ada!. Anything you type after the file name (Ada here) is passed to the program as a command-line argument, available in main through the args array.
Java scripts with a shebang line
On Linux and macOS you can even make a Java file directly executable, like a shell script. The file must not end in .java, and its first line names the launcher and a source version:
#!/usr/bin/env -S java --source 21
public class Greet {
public static void main(String[] args) {
System.out.println("Hi from a Java script, " + String.join(" ", args));
}
}
chmod +x greet
./greet Ada Lovelace
Hi from a Java script, Ada Lovelace
Keeping Source and Class Files Apart
Once programs have more than one class, compiled files clutter your source folder. The -d option tells javac where to put them, and -cp (class path) tells java where to look for them:
javac -d out Greeter.java Messages.java
java -cp out Greeter Bob
Hello, Bob!
out/ now holds Greeter.class and Messages.class. The class path is an important concept that gets its own article in the packages part of the course.
Even Simpler in Java 25: Compact Source Files
Java 25 finalised a feature that removes the boilerplate from small programs. You may leave out the class declaration and write main without public, static or a parameter:
void main() {
IO.println("Hello, Java 25!");
}
java Hello.java
The compiler wraps the code in an implicit class for you, and IO.println is a simple console-printing method in java.lang.IO, also added in Java 25. This is designed for beginners and small scripts. This course mostly uses the full public class … public static void main(String[] args) form, because that's what you'll see in nearly all existing code. The next article on program structure explains both forms in detail.
A Graphical Program
Java programs don't have to print to a terminal. The JDK includes Swing, a toolkit for desktop windows. Save this as ClickCounter.java, then compile and run it like any other program:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
/**
* A tiny graphical program: a window with a label and a button.
* Each click on the button increases the counter shown in the label.
*/
public class ClickCounter {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("Click Counter");
var label = new JLabel("Clicks: 0", SwingConstants.CENTER);
label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 28));
var button = new JButton("Click me");
int[] count = {0};
button.addActionListener(event -> {
count[0]++;
label.setText("Clicks: " + count[0]);
});
frame.add(label, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
javac ClickCounter.java
java ClickCounter
A small window opens with a counter and a Click me button. Close the window to end the program.
The program is longer than Welcome, but think how much code a similar window would take in C or C++ with native APIs, and it runs unchanged on Windows, macOS and Linux. It uses several things you'll learn later: imports, lambdas (event -> { … }), var, and arrays. Desktop GUIs are not the focus of modern Java (most Java runs on servers), so this course doesn't cover Swing further.
Command Cheat Sheet
| Task | Command |
|---|---|
| Check versions | javac --version, java --version |
| Compile one file | javac Welcome.java |
Compile several files into out/ | javac -d out *.java |
| Run a compiled class | java Welcome |
| Run with a class path | java -cp out Greeter |
Pass arguments to main | java Greeter Ada Lovelace |
| Run a source file directly (11+) | java Welcome.java |
| Run a multi-file program from source (22+) | java Greeter.java |
| Show bytecode | javap -c Welcome |
List all javac options | javac --help |
Common questions
Why does java Welcome say "Could not find or load main class"?
The usual causes are, in order: you are in the wrong folder; the capitalisation differs from the class name; you typed .class at the end; or the class is in a package and you didn't use its full name (for example java com.example.Welcome from the folder above com). If you used javac -d out, add -cp out.
Do I still need javac now that java Welcome.java works?
For anything beyond small programs, yes. Source-file mode compiles in memory on every run and doesn't produce class files that you can package or ship. Real projects use a build tool that calls javac. Source-file mode is ideal for exercises, scripts and quick experiments.
Can source-file mode use external JAR libraries?
Yes. Pass the class path as usual: java -cp lib/gson.jar Main.java. Since Java 22, the launcher also compiles other .java files in the same directory tree when they are needed.
How do I compile for an older Java version?
Use javac --release 21 Welcome.java. --release checks your code against the Java 21 language rules and the Java 21 API, so you can't accidentally call a method that only exists in a newer version. It replaces the older -source/-target pair, which didn't check the API.
What does the exit code of java tell me?
It is 0 when main finishes normally, 1 when the program ends because of an uncaught exception, and whatever value you passed to System.exit(n). Scripts and CI pipelines use it to decide whether a step succeeded. Check it with echo $? (macOS/Linux) or echo %ERRORLEVEL% (Windows Command Prompt).
Summary
javaccompiles a file (Welcome.java) into bytecode (Welcome.class);javaruns a class (Welcome) in a new JVM.- Java is case-sensitive; a public class must be in a file with the same name plus
.java. - Don't type
.classafterjava, and don't leave out.javaafterjavac. - Read compiler errors from the top: file, line, message, caret. Fix the first error first.
- Source-file mode (
java Welcome.java) compiles in memory and runs. It works for single files since Java 11 and multiple files since Java 22, and with a shebang line it lets you write Java scripts. javac -d outandjava -cp outkeep compiled classes separate from sources.- Java 25 adds compact source files (
void main() { IO.println(...); }) for small programs.
Practice Questions
Why does javac take Welcome.java but java takes Welcome?
javac works with files: it reads source files from disk, so it needs the file name. java works with classes: it starts a JVM and asks it to load a class by its fully qualified name; the JVM then locates the corresponding .class file using the class path. (The exception is source-file mode, where java is given a .java file to compile in memory.)
You run java welcome and get "NoClassDefFoundError: welcome (wrong name: Welcome)". What happened?
The file system (Windows/macOS) found Welcome.class despite the different capitalisation, but the class inside is named Welcome, not welcome. Java names are case-sensitive, so the JVM rejects it. Run java Welcome.
javac says "file not found: Welcome.java", but you can see the file in File Explorer. What should you check?
Run dir in the terminal. The file is probably Welcome.java.txt (Notepad added .txt and Explorer hid it). Also check that the terminal is in the right folder and that the capitalisation matches.
Your program has 12 compiler errors. What's the best strategy?
Fix the first error and recompile. One mistake, such as a missing brace or semicolon, often confuses the compiler and produces many follow-on errors that vanish once the first is fixed.
What is the difference between java Welcome.java and javac Welcome.java followed by java Welcome?
Both run the program. java Welcome.java (source-file mode) compiles in memory and runs immediately, leaving no .class file. The two-step version writes Welcome.class to disk, so you can run it again later without recompiling, ship it, or put it in a JAR. Real projects use the compile step, usually through a build tool.
What does javac -d out *.java do?
It compiles every .java file in the current folder and writes the .class files into the out directory (creating subfolders for packages). Run the result with java -cp out MainClassName.
Previous: How to Install the Java JDK on Windows, macOS and Linux
Next: Using a Java IDE: IntelliJ IDEA, VS Code and Eclipse for Beginners
Related reading
- JShell Tutorial: Java's Interactive REPL for Quick Experiments
- Using a Java IDE: IntelliJ IDEA, VS Code and Eclipse for Beginners
- How to Install the Java JDK on Windows, macOS and Linux
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.