How to run java program in Command Prompt

There are several ways to run a Java program and CMD is one of the easiest way to compile and run a Java program. 

           In this chapter we will learn how to write, compile and run a Java program in Command Prompt.

                You must follow the steps below to run a Java program.
Step 1Open Code Editor.

          Here we have used Notepad to write code, but you can also use any code editor. To open Notepad press windows logo + r then type notepad and press OK, Alternatively type notepad in the windows search box and click on the Notepad app.
notepad
Step 2 – Write a JAVA program.
  
                    Write the program you want to run, we have written the following code in Notepad which is the sum of two numbers. you can copy the code.

public class TestProgram
{
	public static void main(String[] args)
	{
		int a = 5;
		int b = 8;
		int sum = a+b;
		System.out.println("The sum is = "+sum);
	}
}

 

Step 3 – Save the JAVA program.

              To save a program, press ctrl + s and type TestProgram.java as a file name and click the Save button. Always remember that the name of the Java file must be the same as the name of the class.
Java
                          In the above step we have written and saved a java code, now it is time to compile and run the code.
             
Note:-  We are considering that Java is properly installed in your system.

Step 4 – Open Command Prompt.

                   To compile and run a java program we will use command prompt (cmd). So to open cmd press windows logo + r then type cmd and press OK, Alternatively Type cmd in the windows search box and click on the cmd app.
CMD
        We hope command prompt is open..
cmd
         We have saved our Java program code in the code folder which is located on the desktop. So, use the following code to access the code folder.
      1. cd desktop, then enter.
      2. cd code, then enter.
Note: cd means – change directory, basically we use cd only when we want to move from one directory to another in command prompt.
cmd

Step 5 – Use the following command, To compile the Java program.

      javac TestProgram.java

compile java program
Note:-  If you encounter this ‘”javac” is not recognized as an internal or external command’ error while compiling the code, This means your system may not have JAVA installed or Java is installed but the path is not set in system environment.
              After compile a Java program, it creates a .class file with the same name as the file name at the same location.
java class file

Step 6 – Use the following command, To run the Java program.

    java TestProgram

run java program

                We hope that you have followed the above steps to run a Java program at the command prompt and your written Java program has been successfully compiled and run.

    

Leave a Reply

Your email address will not be published. Required fields are marked *