Open In App

Java Program to Open the Command Prompt and Insert Commands

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the Runtime class allows Java applications to interact with the system’s environment. Every Java application has an object of this class, this class provides exec() method and this method is used to run system commands.

In this article, we will discuss how the exec() method can be used to open the command prompt and run commands.

Syntax of exec() Method

The syntax of exec() method is:

public Process exec(String command)

  • Parameter: This method takes a single parameter, command, which is the command to be executed.
  • Return Type: This method returns a process object that manages the subprocess.
  • Exceptions: This method throws SecurityException, IOException, NullPointerException, and IllegalArgumentException

Opening the Command Prompt in Java

The very first step is to open the Command Prompt. It is done by passing “cmd” command to exec() method.

Example:

Java
// Java program to illustrate
// open cmd prompt
class Geeks
{
    public static void main(String[] args)
    {
        try
        {
            // Just one line and you are done ! 
            // We have given a command to start cmd
            // /K : Carries out command specified by string
           Runtime.getRuntime().exec(new String[] {"cmd", "/K", "Start"});

        }
        catch (Exception e)
        {
            System.out.println("An error occurred while executing the command.");
            e.printStackTrace();
        }
    }
}

When we run this code, it will open a new Commond Prompt window. If there is any issue in the code, the exception will be printed which is “An error occurred while executing the command.”

Note: This code should be executed on a local system. It will not work on an online IDE as it interacts directly with the operating system.

Output:

cmd


Running Commands in the Command Prompt

To execute the commands inside the command prompt we can use Runtime.exec() method. We can perform various commands such as dir, which is used to list all directories and the ping, which is used to test the ability of the source computer to reach a specified destination computer. Now, we will see how we can run multiple commands using exec() method.

Example:

Java
// Java program to illustrate
// executing commands on cmd prompt

class Geeks
{
    public static void main(String[] args)
    {
        try
        { 
         // We are running "dir" and "ping" command on cmd
         Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"dir && ping localhost\"");
        }
        catch (Exception e)
        {
            System.out.println("HEY Buddy ! U r Doing Something Wrong ");
            e.printStackTrace();
        }
    }
}


Output:


RunningVariousCommands


Next Article
Article Tags :
Practice Tags :

Similar Reads