How to Run Java Program from Command Line: Simple Steps
To run a Java program from the command line, first compile the source file using
javac FileName.java. Then, run the compiled program with java FileName without the .class extension.Syntax
Use these commands in your terminal or command prompt:
- Compile:
javac FileName.java- This turns your Java code into bytecode. - Run:
java FileName- This executes the compiled bytecode.
Replace FileName with your actual Java file name without the extension when running.
bash
javac FileName.java java FileName
Example
This example shows a simple Java program that prints a greeting. It demonstrates compiling and running from the command line.
java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world!"); } }
Output
Hello, world!
Common Pitfalls
Common mistakes include:
- Trying to run
java FileName.javainstead of compiling first. - Running
java FileName.classwith the extension, which is incorrect. - Not being in the directory where the
.javafile is located. - Forgetting to set the
PATHenvironment variable to include the Java compiler and runtime.
bash
Wrong: java HelloWorld.java Right: javac HelloWorld.java java HelloWorld
Quick Reference
| Command | Purpose |
|---|---|
| javac FileName.java | Compile Java source code to bytecode |
| java FileName | Run the compiled Java program |
| java -version | Check installed Java version |
| javac -version | Check installed Java compiler version |
Key Takeaways
Always compile your Java file first using javac before running it.
Run the program using java with the class name only, no file extension.
Make sure your terminal is in the directory containing your Java file.
Set your PATH environment variable to include Java tools for easy access.
Use java -version and javac -version to verify your Java installation.