Home Java Learn-java-in-a-day Add Two Numbers in Java



Add Two Numbers in Java
Posted on: February 25, 2008 at 12:00 AM
In this section, you will learn to work with command prompt arguments provided by the user. We will access these arguments and print the addition of those numbers. In this example, args is an array of String objects that takes values provided in command

Add Two Numbers in Java

     

In this section, you will learn to work with command prompt arguments provided by the user. We will access these arguments and print the addition of those numbers. In this example, args is an array of String objects that takes values provided in command prompt. These passed arguments are of String types so these can't be added as numbers. So to add, you have to convert these Strings in numeric type (int, in this example). Integer.parseInt helps you to convert the String type value into integer type. Now you can add these values into a sum variable and print it on the console by println() function.

Here is the code of program:

public class AddNumbers{
  public static void main(String[] args) {
  System.out.println("Addition of two numbers!");
  int a = Integer.parseInt(args[0]);
  int b = Integer.parseInt(args[1]);
  int sum = a + b;
  System.out.println("Sum: " + sum);
  }
}

Download this example.

Output of program:

C:\vinod>javac AddNumbers.java

C:\vinod>java AddNumbers 12 20
Addition of two numbers!

Sum: 32

Related Tags for Add Two Numbers in Java:
cstringcomidearrayfunctionconsolestringsobjectconvertfunioobjectstypesparsehelpintegervariableusersedprintargumentstypecommandnumbersvivaluenumbersumoleintriathisidpromptexampleuncaddwithworknumericvaluestolearnexamsseargumenteareilitsectioncommacanvarusepemanceddeinnopassasmntparpstroscaddadditionoslnjadesfuncargsmeintoobjproxaxampssusoessataddedkishallmplrayparseinteaandarccconsstrrtvassrirgsringthavstaccessabablaluhatctsintljepleplprndonomolo


More Tutorials from this section

Ask Questions?    Discuss: Add Two Numbers in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.