How to run Java Program in Command Prompt

In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt.

Note: One must ensure that Java is installed in one’s system and PATH variable is set properly. To check whether the PATH variable is set or not, open the command prompt by writing cmd in the search area of the taskbar and press enter.

The other approach to open the command prompt is to press Windows + R, then type cmd and press the OK button.

 In the command prompt, type the command javac and press enter.

If the PATH variable is set properly, the information mentioned in the above snapshot is shown; otherwise, the command not found! message is shown.

After checking for the javaccommand, enter the command java and press enter.

Observe that after the command java, some information is shown. It denotes that Java is installed in the system.

Choosing Text Editor

To write a Java program, a text editor is required. Any editor of one’s choice does the job. However, in this section, we will stick with notepad++.

In the search area of the taskbar enter notepad++ and press enter.

or press Windows + R, then type notepad++ and press the OK button.

After pressing enter key or OK button, it opens the notepad++.

Now, write any Java program on one’s choice. Let’s write a simple Hello-World Java program.

FileName: HelloExample.java

Save the file and provide the name of the file. The name of the file should match with the class name. The extension of the file has to be .java. We have saved it to the Java folder of the D drive.

Now, open the Command Prompt.

Now move to the folder where we save our file. Currently, drive C is selected. Therefore, first, we have to change our drive from C to D.

Type D: and press enter to change the drive from C to D.

Now, we have to select the Java folder where we saved our file. Type cd Java and press enter.

Eventually, we have reached our destination folder. Now, to compile the file, use the javac command along with the filename and its extension, and press enter.

If the code is error-free, we get a .class file. Otherwise, a compilation error is shown by the compiler, and .class file does not get generated. The compilation error must be resolved to proceed further.

After the compilation step comes the execution step. To execute a Java program, the java command is used along with the file name. This time the extension of the file is excluded.

On execution, the program prints the welcome statement.

Pin It on Pinterest

Share This