How to run a Java program in the command prompt? Java, a widely used programming language, offers a versatile platform for developing various applications, from simple command-line tools to complex enterprise-level software. Running Java programs via the command prompt or terminal is a fundamental skill for Java developers. This article will guide you through the step-by-step process of executing Java programs using the command prompt in Windows, macOS, or Linux.
Table of Contents
Prerequisites
Before running a Java program from the command prompt, ensure that the Java Development Kit (JDK) is installed on your system. To check if Java is installed, open the command prompt or terminal and type:
java -version
You will get the following result if JDK is installed in your system
If Java is installed, this command will display the installed version. If not, visit the official Oracle Java website or adopt OpenJDK to download and install the JDK appropriate for your operating system.
Writing a Simple Java Program
Let’s begin by creating a simple Java program using a text editor or an Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code.
Example Java program (HelloWorld.java)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Save this program with the filename HelloWorld.java
.
Running Java Programs from the Command Prompt
Step 1: Compile the Java Program
Open the command prompt or terminal in the directory containing your Java file (HelloWorld.java
). Use the javac
command, the Java compiler, to compile the Java source code into bytecode:
javac HelloWorld.java
If there are no syntax errors in your code, this command will generate a HelloWorld.class
file containing bytecode.
Step 2: Execute the Java Program
After successfully compiling the Java file, execute the program using the java
command followed by the class name (excluding the .class
extension):
java HelloWorld
Running this command will execute the main
method within the HelloWorld
class, resulting in the output:
Additional Notes
- Classpath: For programs using external libraries or packages, include the classpath using the
-cp
or-classpath
option followed by the directory or JAR file containing the required classes. - Package Structure: If your Java file is within a package (i.e., not in the default package), ensure the directory structure reflects the package structure and use the appropriate package declaration in your Java file.
- Environment Variables: Ensure that the Java bin directory is added to the system’s
PATH
variable for seamless execution from any directory.
1 thought on “Running Java Programs Using Command Prompt: A Step-by-Step Guide”