Monday, 3 July 2017

How to pass command line arguments in Eclipse

Eclipse is one of the most preferred IDE for Java/JEE development. Eclipse IDE provides various options like running the application from the IDE, providing arguments to your Java program, debugging your application.

In this post we’ll see how to pass program arguments to your Java program.

Passing arguments

Let’s take an example Java program where you have to add the two passed arguments and print the total.

Example code

public class Add {

 public static void main(String[] args) {
  try{
   if(args.length != 2){
    throw new IllegalArgumentException("Argument length "
      + "should be 2 ");
   }
  }catch(IllegalArgumentException IAexp){
   System.out.println("Error in the code - " + IAexp.getMessage()); 
  }
  double total = Double.parseDouble(args[0]) + 
      Double.parseDouble(args[1]);
  System.out.println("Sum of " + args[0] + " and " 
      + args[1] + " is: " + total);

 }

}

How to provide arguments

You can select “Run Configuration” option by selecting the Run menu from the top menu.

Selecting Run Configuration option from Run menu

You can also select the same “Run Configuration” option by right clicking the program for which you have to provide args, from the package explorer.

command line arguments in eclipse
Selecting Run Configuration option from package explorer

That will open the “Run Configuration” screen.

Run Configuration screen

Make sure that the program where arguments are to be passed is selected.If you don’t find your program there search for it or add it by right clicking on “Java Application” and selecting New.

In the “Run Configuration” screen select the “Arguments” tab and provide required arguments in the “Program arguments” text area. Then select Apply and then Run to run you program.

That's all for this topic How to pass command line arguments in Eclipse. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating a Maven project in Eclipse
  2. Why file name and class name should be same in Java
  3. Why main method static in Java
  4. Java pass by value or pass by reference

You may also like -

No comments:

Post a Comment