Sunday, August 23, 2015

Java program to add two numbers

Given below is the code of java program that adds two numbers which are entered by the user.

Java programming source code


import java.util.Scanner;
 
class AddNumbers
{
 public static void main(String args[])
 {
 int x, y, z;
 System.out.println("Enter two integers to calculate their sum ");
 Scanner in = new Scanner(System.in);
 x = in.nextInt();
 y = in.nextInt();
 z = x + y;
 System.out.println("Sum of entered integers = "+z);
 }
}

Output of program:


Above code can add only numbers in range of integers(4 bytes), if you wish to add very large numbers then you can use BigInteger class. Code to add very large numbers:

import java.util.Scanner;
import java.math.BigInteger;
 
class AddingLargeNumbers {
 public static void main(String[] args) {
 String number1, number2;
 Scanner in = new Scanner(System.in);
 
 System.out.println("Enter first large number");
 number1 = in.nextLine();
 
 System.out.println("Enter second large number");
 number2 = in.nextLine();
 
 BigInteger first = new BigInteger(number1);
 BigInteger second = new BigInteger(number2);
 BigInteger sum;
 
 sum = first.add(second);
 
 System.out.println("Result of addition = " + sum);
 }
}

In our code we create two objects of BigInteger class in java.math package. Input should be digit strings otherwise an exception will be raised, also you cannot simply use '+' operator to add objects of BigInteger class, you have to use add method for addition of two objects.

Output of program:
Enter first large number
11111111111111
Enter second large number
 99999999999999
Result of addition = 111111111111110

Related Posts:

  • Java methods Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will… Read More
  • Java static block program Java programming language offers a block known as static which is executed before main method executes. Below is the simplest example to understand f… Read More
  • Java program to find odd or even This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operat… Read More
  • Java program to swap two numbers This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below. Swapping u… Read More
  • How to get input from user in java This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the… Read More

0 Comments:

Post a Comment