Running a Java program from the terminal is a fundamental skill that every developer must master, whether you are a student writing your first "Hello World" or a seasoned engineer debugging a production issue on a headless server. While Integrated Development Environments (IDEs) like IntelliJ IDEA or Eclipse abstract this process away with a single green play button, understanding the underlying commands—javac for compilation and java for execution—gives you complete control over the build lifecycle. This guide provides a comprehensive walkthrough of how to run a Java file in the terminal, covering everything from basic single-file execution to handling packages, external libraries, and common troubleshooting scenarios Less friction, more output..
Prerequisites: Verifying Your Java Installation
Before attempting to compile or run any code, you must ensure the Java Development Kit (JDK) is correctly installed and configured in your system’s PATH. The JDK includes the compiler (javac) and the runtime (java), whereas the Java Runtime Environment (JRE) only allows you to run pre-compiled programs.
Open your terminal (Command Prompt or PowerShell on Windows, Terminal on macOS/Linux) and type the following commands:
java -version
javac -version
If both commands return version numbers (e.g.Worth adding: , openjdk version "21. But 0. Plus, 2"), you are ready to proceed. If you receive a "command not found" or "not recognized as an internal command" error, you need to install the JDK and add its bin directory to your system's environment variables And that's really what it comes down to..
The Two-Step Process: Compile Then Run
Java is a compiled language. class files) using the Java Compiler (javac). Because of that, java source file directly. You must first translate the human-readable source code into platform-independent bytecode (.Day to day, unlike Python or JavaScript, you cannot execute a . Then, the Java Virtual Machine (JVM) interprets that bytecode via the java command.
Step 1: Create a Simple Source File
Create a file named HelloWorld.Day to day, java using any text editor (VS Code, Notepad, Vim, Nano). Ensure the filename matches the public class name exactly, including case sensitivity Simple, but easy to overlook..
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Terminal!");
}
}
Step 2: Compile the Source Code
deal with to the directory containing your file using the cd command. Run the compiler:
javac HelloWorld.java
If the command returns immediately with no output, compilation was successful. A new file named HelloWorld.This file contains the bytecode. class has been generated in the same directory. If there are syntax errors, the compiler will output line numbers and descriptions to help you fix them.
Step 3: Run the Compiled Bytecode
Now, execute the program using the java command. Crucial Note: You provide the class name, not the filename. On the flip side, do not include the . class extension.
java HelloWorld
Output:
Hello, Terminal!
Managing Output with the -d Flag
By default, javac places .Best practice dictates separating source files from compiled artifacts. Plus, for larger projects, this clutters your source tree. class files in the same directory as the source code. Use the -d (destination) flag to specify an output directory (conventionally named out or build).
This changes depending on context. Keep that in mind.
mkdir out
javac -d out HelloWorld.java
This creates the directory structure out/HelloWorld.class. To run it, you must tell the JVM where to find the class files using the -cp (classpath) or --class-path flag:
java -cp out HelloWorld
Working with Packages
Real-world Java applications organize code into packages to avoid naming conflicts and group related functionality. This changes the directory structure and the commands required That's the part that actually makes a difference..
Directory Structure
If your class belongs to a package com.example.app, the file must physically reside in a mirrored directory structure: com/example/app/HelloWorld.java.
project-root/
├── src/
│ └── com/
│ └── example/
│ └── app/
│ └── HelloWorld.java
└── out/ (created during compilation)
Source Code with Package Declaration
package com.example.app;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Running from a package!
### Compiling Packaged Code
You must compile from the **root of the source tree** (usually the `src` directory or project root) so the compiler can resolve the package hierarchy.
```bash
# From project-root directory
javac -d out src/com/example/app/HelloWorld.java
Running Packaged Code
When running, you must use the Fully Qualified Name (FQN) of the class (package name + class name) and set the classpath to the output directory root (out) And it works..
java -cp out com.example.app.HelloWorld
Common Mistake: Trying to cd into out/com/example/app and running java HelloWorld. This fails with NoClassDefFoundError because the JVM expects the folder structure to match the package declaration starting from the classpath root.
Handling Multiple Files and Dependencies
As projects grow, you will have multiple .java files referencing each other. You do not need to list every file manually Small thing, real impact. That's the whole idea..
Compiling Multiple Files
You can use wildcards or argument files. The simplest approach for small projects is compiling all java files in the source tree recursively:
# Linux/macOS (using find)
find src -name "*.java" > sources.txt
javac -d out @sources.txt
# Windows (PowerShell)
Get-ChildItem -Recurse -Filter *.java -Path src | ForEach-Object { $_.FullName } > sources.txt
javac -d out @sources.txt
Alternatively, if you are in the src directory:
javac -d ../out com/example/app/*.java
Including External Libraries (JARs)
Most projects depend on third-party libraries (e.jarfiles. Even so, g. , Gson, Jackson, database drivers) packaged as.You must add these to the classpath during both compilation and runtime.
Assume you have a lib folder containing gson-2.10.1.jar.
Compilation:
# Linux/macOS (colon separator)
javac -cp "lib/gson-2.10.1.jar" -d out src/com/example/app/HelloWorld.java
# Windows (semicolon separator)
javac -cp "lib/gson-2.10.1.jar" -d out src/com/example/app/HelloWorld.java
Execution:
The classpath must include both your compiled classes (out) and the external JARs That's the part that actually makes a difference..
# Linux/macOS
java -cp "out:lib/gson-2.10.1.jar" com.example.app.HelloWorld
# Windows
java -cp "out;lib/gson-2.10.1.jar" com.example.app.HelloWorld
Pro Tip: Use a wildcard (*) to include all JARs in a directory (supported in Java 6+):
java -cp "out:lib/*" com.example.app.HelloWorld
Note: On Linux/macOS, you often need to wrap the classpath in quotes to prevent the shell from expanding the * wildcard before passing it to Java.
Passing Command-Line Arguments
The main method accepts a String[] args parameter. Any strings typed after