A2oz

How to Run a Java Program in Command Prompt?

Published in Programming 2 mins read

To run a Java program in the command prompt, follow these steps:

  1. Compile your Java code: Use the javac command to compile your Java file. For example:

    javac MyProgram.java

    This will create a .class file containing the compiled bytecode.

  2. Run the compiled program: Use the java command to execute the compiled class file. For example:

    java MyProgram

    Replace MyProgram with the name of your class file (without the .class extension).

Important points to remember:

  • Ensure that your Java Development Kit (JDK) is properly installed and configured.
  • The javac and java commands should be accessible from your command prompt environment.
  • The Java file and the compiled .class file must be in the same directory.
  • If your program requires any external libraries, include them in the classpath.

Example:

Let's say you have a Java file named HelloWorld.java with the following code:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

To run this program:

  1. Open your command prompt.
  2. Navigate to the directory containing HelloWorld.java.
  3. Compile the code: javac HelloWorld.java
  4. Run the compiled program: java HelloWorld

You will see the output: Hello, World!

Practical insights:

  • You can use an IDE like Eclipse or IntelliJ IDEA for a more convenient development experience. These IDEs provide integrated tools for compiling, running, and debugging Java code.
  • The -cp or -classpath option can be used with the java command to specify the location of external libraries or JAR files.

Related Articles