Wednesday, 14 March 2018

Add two numbers with all corner case scenarios.

Corner cases
1. Both numbers are negative
a. Sum is negative - Will work fine
b. Sum is positive -
If the sum is positive or zero, this is only possible when the number is out of Max Integer range.
2. Both numbers are negative
a. Sum is positive - Will work fine
b. Sum is negative -
If the sum is negative, this is only possible when the number is out of Min Integer range.

/**
*
* @param a
* @param b
* @return sum
*/
private static int add(int a, int b) {

int sum = a + b;
boolean flag = true;

if ((flag = a > 0 && b > 0) || (a < 0 && b < 0)) {
if ((flag && sum < 0) || (!flag && sum >= 0)) {
throw new ArithmeticException("Overflow");
}
}
return sum;
}

/**
* Driver method.
*
* @param args
*/
public static void main(String[] args) {

System.out.println("Sum 1 " + sum1);

System.out.println("Sum 2 " + sum2);

// Overflow due to both minimum negative values.
try {
} catch (Exception e) {
System.err.println(e.getMessage());
}

// Overflow due to both maximum positive values.
try {
} catch (Exception e) {
System.err.println(e.getMessage());
}