Please wait ......

Passing multiple input arguments to a Java program

Learn how to pass multiple input arguments to a Java program


We will now pass two numbers to a Java class called SumCalculator.java which will add and print the sum.

Note: Please refer previous chapter on how to create a class file in NetBeans

  • Create the Java class SumCalculator.java and create a main method with the following code (Note that we have metioned the package as com.skillrack.examples)
package com.skillrack.examples;

public class SumCalculator {
    public static void main(String[] args) {
        System.out.println(args[0]+args[1]);
    }
}

As we know from previous chapters, args[0] will represent the first input (first number) and args[1] the second number

Now mention the input in the "Run" configuration as shown in the screenshot.

 

Now run the program by clicking on the Run button (Refer previous chapters to know about Run button).

You would expect 100 to be printed. But the output is 595. Java just considered the input values as String and just concatenated them.

 

So how to proceed?

We need to convert the String value to suitable representation. Here as we are dealing with numbers we will use int. (We will explain more about data type conversion in subsequent chapters).

The revised program is as below.

package com.skillrack.examples;

public class SumCalculator {
    public static void main(String[] args) {
        int firstNumber=Integer.parseInt(args[0]);
        int secondNumber=Integer.parseInt(args[1]);
        
        System.out.println(firstNumber+secondNumber);
    }
}

Now when we run this program it gives the expected output which is 100.

Watch the video explaining the sequence: