How To Run A Java Program Using Command Prompt
Run a Java Program using Command Prompt:
We use Java compiler javac to compile Java program and the Java interpreter java to run the Java program.
Goal: To run a Java program using Command Prompt.
Steps to achieve our goal:
i. Create a folder
ii. Create a java class and write a java program
iii. Open command prompt
iv. Run the created Java program using command prompt
Step i: Create a folder
C:\SoftwareTestingMaterial
Step ii: Create a java class and write a java program
Using Notepad or another text editor, create a Java file HelloTesters.java with the following text:
public class HelloTesters{ public static void main(String[] args){ System.out.println("This is SoftwareTestngMaterial website!"); } }
Save your file as HelloTesters.java in C:\SoftwareTestingMaterial.
Step iii: Open command prompt
Open Command Prompt (Open Run (Windows+R) and type cmd)
Step iv: Run the created Java program using command prompt
Follow the below steps:
C:\Users\Admin> cd\
C:\> cd SoftwareTestingMaterial
This makes C:\SoftwareTestingMaterial the current directory.
C:\SoftwareTestingMaterial> dir
This displays the directory contents. You should see HelloTesters.java among the files.
C:\SoftwareTestingMaterial> set path=%path%;C:\Program Files\Java\jdk1.8.0_101\bin
(use the JDK folder for the version installed on your system). This tells the system where to find JDK programs.
C:\SoftwareTestingMaterial> javac HelloTesters.java
This runs javac.exe, the compiler. You should see nothing but the next system prompt.
C:\SoftwareTestingMaterial> dir
javac has created the HelloTesters.class file. You should see HelloTesters.java and HelloTesters.class among the files.
C:\SoftwareTestingMaterial> java HelloTesters
This runs the Java interpreter. You should see the program output:
Output:This is SoftwareTestngMaterial website!
Note:
i. Java is case-sensitive! Check your Java text. Check the spelling and capitalization in the file name and the class name and the java HelloTesters command.
ii. In “Step iv”, we set the jdk path. It is possible to make the path setting permanent but you have to be very careful because your system might crash in case of any mistake. Proceed with extreme caution!
To ensure that Windows can find the Java compiler and interpreter:
Select Start -> Computer -> System Properties -> Advanced System Settings -> Environment Variables -> System Variables -> PATH
Click “Edit” and at the end append the jdk path after semicolon ( ; )
C:\Program Files\Java\jdk1.8.0_101\bin
Note: Add jdk path based on your system jdk path
Click on OK.
Also find How To Run TestNG Using Command Prompt