All Posts

Java program to add two numbers

Java program to add two numbers

In this tutorial, we will write a simple Java program to add two numbers and display the result on the screen.

Problem statement

  • Write a simple Java program to add two integers.
  • Run the program with one positive test case and one negative test case.

Tools used

  • JDK(Java Development Kit)
  • We can use an IDE like IntelliJ IDEA or Eclipse
  • Windows 10

Flow Chart

A flow chart for the program depicts the steps involved. Start Take input two numbers a,b Compute the sum sum = a + b Display the sum Terminate    
Add Two Numbers Flow Chart

IDE Setup

Some steps and instructions to create a Java application on Eclipse IDE:
  • Create Java Project in Eclipse
https://www.testingdocs.com/create-a-new-java-project-in-eclipse/
  • Create Java Package in Eclipse
https://www.testingdocs.com/create-java-package-in-eclipse-ide/
  • Create Java Class in Eclipse
https://www.testingdocs.com/create-a-new-java-class-in-a-project/
  • Run Java Project in Eclipse
https://www.testingdocs.com/run-java-project-in-eclipse/

Java Program

The program prompts the user to enter two numbers. (a,b) The program computes the sum of the two numbers and displays the result to the screen. The program uses the Scanner class to take input from the keyboard which is the standard input device.  
import java.util.Scanner;

public class AddTwoNumbers {

    public static void main(String args[]) {
        Scanner input = null;
        int a,b, sum;
        try {
            input = new Scanner(System.in);
            System.out.print("Enter a:");
            a = Integer.parseInt(input.nextLine());

            System.out.print("Enter b:");
            b = Integer.parseInt(input.nextLine());

            sum = a + b ;
            System.out.print("Sum =" + sum );

        } catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("Error!");
        }
        finally
        {
            if (input != null) {
                input.close();
            }
        }
    }
}

Sample Run output

Save the program in the IDE. Run the program and execute test cases to verify the result of the program.  
Add two numbers java program

Positive testcase

Enter a: 25 Enter b: 50 Sum = 75

Negative testcase

Enter a: invalid input java.lang.NumberFormatException: For input string: ” invalid input” at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:569) at java.lang.Integer.parseInt(Integer.java:615) at com.testingdocs.simpleproject.AddTwoNumbers.main(AddTwoNumbers.java:13) Error!