Using Command-Line Arguments in Eclipse

Suppose you write the following program to add two numbers:

public class SumFinder {

    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int sum = a + b;
        System.out.println(sum);
    }

}

We can see, by the use of args[0] and args[1] above, we need to provide these two numbers as command-line arguments to our java program.

To run this program to find the sum of $2$ and $3$ (and assuming we had already executed javac SumFinder.java), we could type at the command-line prompt:

$ java SumFinder 2 3


Recall that in Eclipse, java programs are run a bit differently -- we typically either click the little green "Run" button, or use the keyboard-shortcut "Shift-Cmd-F11".

Unfortunately, neither of these two techniques give the user any opportunity to provide command-line arguments to the program. Fear not however -- we can fix that!

The below instructions demonstrate how a program's "run configuration" within Eclipse can be altered to prompt the user for a string of text to be used as the command-line arguments for a given program:

  1. First, create a new java project in Eclipse, and then within that folder, create a new class called SumFinder. Replace any existing code in the SumFinder class file with the code given at the top of this page.

  2. Next, from the "Run" menu, select "Run Configurations..."

  3. Under "Java Application" on the left side of the window, select the program whose configuration you wish to change -- in this case, "SumFinder".

  4. Now click on the "Arguments" tab.

  5. In the text-box labeled "Program arguments:", type ${string_prompt} as shown below


  6. Click the "Apply" button.

  7. Finally, click the "Close" button.

Now, from this point forward, every time you run that particular program you will be immediately prompted to enter any command-line arguments it needs to run, as shown below.