Java program to add two numbers

Hey guys!! Welcome to flower brackets blog. Java program to add two numbers is one of the common java interview question.

In this java program we are taking input from user. Because we are asking user to input values to add two numbers in java.

Also read Рjava program to add two numbers using method

Let’s see an example on addition of two numbers in java,

import java.util.Scanner;

public class AddTwoNumbers
{
   public static void main(String[] args)
   {
      int a, b, c;
      System.out.println("Please enter two integers to add : ");
      Scanner sc = new Scanner(System.in);

      a = sc.nextInt();
      b = sc.nextInt();
      c = a + b;

      System.out.println("Sum of Two Integers = " + c);
      sc.close();
   }
}

Output:

Java Program To Add Two Numbers


Add two numbers in java using BigInteger class

Here we create objects of BigInteger class. Then two string variables is created to store input values entered by user.

Notice that data type is of type String. Because if you use other data type exception is thrown. Finally add() method is used to add two large numbers.

import java.math.BigInteger;
import java.util.Scanner;

public class BigIntegerDemo
{
   public static void main(String[] args)
   {
      String num1, num2;
      Scanner sc = new Scanner(System.in); 
      System.out.println("Please enter first number : ");
      num1 = sc.nextLine();
      System.out.println("Please enter second number : ");
      num2 = sc.nextLine();
      BigInteger obj1 = new BigInteger(num1);
      BigInteger obj2 = new BigInteger(num2);
      BigInteger total;
      total = obj1.add(obj2);
      System.out.println("Result : " + total);
      sc.close();
   }
}

Output:

Please enter first number : 2222222222
Please enter second number : 3333333333
Result : 5555555555

Related Posts