How to Compile and Run a Java Program: Simple Steps
To compile a Java program, use the
javac command followed by the file name, like javac MyProgram.java. Then, run the compiled program with java MyProgram without the .java extension.Syntax
To compile a Java file, use the javac command followed by the file name with the .java extension. This creates a bytecode file with the .class extension.
To run the compiled program, use the java command followed by the class name without the .class extension.
bash
javac FileName.java java FileName
Example
This example shows a simple Java program that prints a greeting message. It demonstrates how to compile and run the program using the command line.
java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world!"); } }
Output
Hello, world!
Common Pitfalls
- Forgetting to save the file with the exact class name and
.javaextension causes compilation errors. - Running
javawith the file name including.javaor.classwill fail; use only the class name. - Not having Java installed or not setting the PATH environment variable correctly will cause commands to fail.
bash
/* Wrong way: including extension when running */ // java HelloWorld.java <-- This will cause an error /* Right way: omit extension */ // java HelloWorld
Quick Reference
| Command | Description |
|---|---|
| javac FileName.java | Compile Java source code into bytecode (.class file) |
| java FileName | Run the compiled Java program by class name |
| java -version | Check installed Java version |
| javac -version | Check installed Java compiler version |
Key Takeaways
Use
javac FileName.java to compile your Java program.Run the program with
java FileName without the file extension.Save your file with the exact class name and .java extension.
Ensure Java is installed and PATH is set to use
javac and java commands.Avoid including file extensions when running the Java program.