0
0
JavaHow-ToBeginner · 3 min read

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 .java extension causes compilation errors.
  • Running java with the file name including .java or .class will 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

CommandDescription
javac FileName.javaCompile Java source code into bytecode (.class file)
java FileNameRun the compiled Java program by class name
java -versionCheck installed Java version
javac -versionCheck 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.