DEV Community

Kavitha
Kavitha

Posted on

How to Compile and Run a Java Program Using Command Line

  • Compiling and running Java programs from the command line helps you understand how Java works internally and is essential for interviews, debugging, and real-world development.

Prerequisites

  • Java JDK installed

Steps to follow
Step 1: Create a Java Program

  • Create a file named HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Important: The file name must match the class name.

Step 2: Open Command Prompt / Terminal

  • Navigate to the folder where the .java file is saved.
  • Type cmd on the path bar


-Command prompt gets opened

Step 3: Compile the Java Program

  • Use the javac compiler:
javac HelloWorld.java

Enter fullscreen mode Exit fullscreen mode

What Happens Internally?

  • javac checks syntax
  • Converts source code into bytecode
  • Generates a file: HelloWorld.class

Step 4: Run the Java Program

Use the java command (without .class):

java HelloWorld

Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Java!

Enter fullscreen mode Exit fullscreen mode

*Compilation Flow *

  • .java file → Source code
  • javac → Bytecode (.class)
  • java → JVM loads and executes bytecode

Top comments (0)