How to run Java Program

In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad.

In order to run a Java program, we have to install JDK (Java Development Kit) in oursystem that provides the runtime environmentfor the applications. After the JDK installation, path must be set properly otherwise we cannot run the code. There are two ways to set the path of JDK, click here to learn.

Follow the steps given below to run a Java program:

  • Open Notepad.
  • Write a Java program into it, and save the file with the extension .java

Note: The name of the file should be same as that of the class name.

  • Open the command prompt (CMD), enter the commands and run the Java program.

Note: Before moving ahead in this section, ensure that JDK is successfully installed and class path is properly set.

Let’s follow below steps to run a Java program:

Step 1: Open the Code Editor and type the basic Java code. Save the file with the name MyJavaProgram.java.

Step 2: Open the Command Prompt. Set the directory where we have saved the Java file. In our case, the Java file is saved in D:\Project directory.

run Java Program

Step 3:First, we will compile the Java program by using the javac command.

It generates a .class (byte code) file in the same folder. If there is any error in the code, it shows that error with line number.

run Java Program

Oncewe resolve the error and run the command again, a .class file will be created in the same folder (D:\Programs).

run Java Program
run Java Program

Step 4: To run the .class file (byte code), we use the java command followed by the class name.

Once the program is error free, and the class file is created, the Java program runs successfully, as shown below:

run Java Program

Note: You can also a run the Java program directly using different user-friendly code editors like Visual Studio Code, Eclipse, Atom, etc. as these editors have their own virtual environments to run the program.

In this way, we have learned how to run a Java Program.

Pin It on Pinterest

Share This