How to compile & run a Java program using Command Prompt?



Command prompt is a command line interface that accepts text-based inputs or commands and performs tasks based on those command. Nowadays, there are various integrated development environments (IDEs) that are available to compile, build, and run Java programs within their environment. However, we can also compile and run Java programs using the Command Prompt.

Compiling and Running Java Programs using CLI

To compile and run Java programs outside the IDEs using the Command Prompt, we need to install the JDK and set its path in our system. To set up the development environment for Java on your local machine, we recommend the Environment Setup chapter of our Java tutorial.

After installation, follow the steps given below:

  • Step 1: Create a Java program either in Notepad or another IDE.

  • Step 2: Next, create a folder and save this Java file inside it with the same name as of Java class (that contains main() method) you created in the program. The extension of the Java file should be ".java".

  • Step 3: Now, compile this Java file from the command prompt using the javac command.

  • Step 4: Once the compilation is successful, you can see a compiled file generated with the extension ".class".

  • Step 5: To execute or run this Java file using the command prompt, just type the JAVA command followed by the file name without ".java" extension.

  • Step 6: At the end, you can see the output in the console.

Example

In this example, we will create a Java program with a public class Demo and run this program using the CLI.

public class Demo{
   public static void main(String args[]){
      System.out.println("Welcome to Tutorials Point");
   }
}

Now, save this file with the name Demo.java inside a folder named "Java programs". After saving the file, open Command Prompt and navigate to the folder where you have saved the file as shown below:

cd Java programs

Next, compile the code using the javac command:

javac Demo.java

Finally, run the code using the Java command:

java Demo

On running the Java program, you will get the following result in the console:

Welcome to Tutorials Point
Updated on: 2025-04-24T18:17:52+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements