0
0
JavaHow-ToBeginner · 3 min read

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.java instead of compiling first.
  • Running java FileName.class with the extension, which is incorrect.
  • Not being in the directory where the .java file is located.
  • Forgetting to set the PATH environment variable to include the Java compiler and runtime.
bash
Wrong:
java HelloWorld.java

Right:
javac HelloWorld.java
java HelloWorld
📊

Quick Reference

CommandPurpose
javac FileName.javaCompile Java source code to bytecode
java FileNameRun the compiled Java program
java -versionCheck installed Java version
javac -versionCheck 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.