Monday, 10 September 2012

Adding two numbers using IInd Method(J2SE)

Adding two numbers
J2SE Programming

Now m going to write the program for adding two numbers using values via command line arguments.
Command-Line arguments are the arguments which are passed just before run time i.e. after compilation.
Now the problem is how to get the arguments via command line.
Command Line arguments are passed in the String array used in main function as an argument.
Now the numbers are passed as string and we want int then what to do for this.
We have a static method in Integer class i.e. parseInt(String) which takes an argument of type string an returns int and there is a condition that the string passed in this should have a valid int value otherwise there is an run time exception i.e. NumberFormatException.

Here is the program for this:-

                                       class abc                                        
                                               int a,b,sum;

                                              public static void main(String[] args)

                                                  a=Integer.parseInt(args[0]);      //Getting int from string array at position 0

                                                  b=Integer.parseInt(args[1]);     //Getting int from string array at position 1

                                                  sum=a+b;                               //Adding numbers

                                                  System.out.println("Sum = "+sum);            // Printing sum


Now how to pass value in that string array.
Here is the solution:-

Firstly compile it as usual using Javac
Now Run using java program arg1 arg2
arg1 arg2 are the arguments which are the a and b.

For further queries, feel free to contact us any time using our contact us form.
Thank You.


Post a Comment