June 29, 2022

How to Pass Command Line Arguments in Eclipse

In this tutorial we’ll see how to pass command line arguments in Eclipse IDE. You can pass command line arguments to a Java program. Command line arguments are converted to String and stored in an array that is passed to the main method. That is why syntax of main method is as follows-

Public static void main(String[] args)

Passing command line arguments in Eclipse

Eclipse IDE also provides the facility to pass command line arguments to a Java program. In order to see how to do that let’s take the following program as an example that takes 2 command line arguments and prints the sum.

public class Sum {

  public static void main(String[] args) {
    try{
      if(args.length != 2){
        throw new IllegalArgumentException("Two Arguments required");
      }
      // If argument passed can't be parsed into a number NumberFormatException is thrown
      double total = Double.parseDouble(args[0]) + Double.parseDouble(args[1]);
      System.out.println("Sum of " + args[0] + " and " + args[1] + " is: " + total);
    }catch(IllegalArgumentException e){
      System.out.println("Error- " + e.getMessage()); 
    }
  }
}

Select Run – Run Configurations from the top menu.

Run configurations

You can also select Run Configurations by right clicking the program in the project explorer and selecting Run – Run Configurations

Eclipse run configuration

In the Run Configurations window make sure correct program, for which you want to specify command line arguments, is selected. If not then select the correct program by searching for it. Select the arguments tab and enter the arguments separated by space in the “Program arguments” area.

Command line arguments in eclipse

Select Apply and then Run to execute you program.

Arguments written in the “Program arguments” window are passed to the String[] args array in the main method of your program and you can access them by using the args array.

That's all for the topic How to Pass Command Line Arguments in Eclipse. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment