Write a simple java program to add two numbers?

Problem statement
a)Write a simple java program to add two integers.
b)Run the program with one positive test case and one negative test case.

In this program, we will compute the sum of two integers and display the result in a java program.

Flow Chart

Flow chart for the program depicting the steps involved.

Take input two numbers a,b
Compute the sum sum = a + b
Display the sum


Add Two Numbers Flow Chart

Java Program to Add Two integers

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(); } } }


Run output

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)