An int silently wraps around when a result is too large. Show what happens and detect it.
What to build
A program that adds and multiplies two ints and reports any overflow.
Requirements
- Read two ints a and b.
- Print
sum: S (int: X)where S is the true sum and X the int result, thenproduct: P (int: Y)likewise. - Then print
overflow in:followed bysum,product,sum, productornothing.
Input
One line: a and b.
Output
Three lines.
Constraints
a and b fit in an int.
Example
Input:
3 4
Output:
sum: 7 (int: 7)
product: 12 (int: 12)
overflow in: nothing
Why it works
Doing the same calculation in long, which is wide enough for any sum or product of two ints, gives the true value; when the int result differs, it has wrapped around.
Examples
Example 1 · Input
3 4
Expected output
sum: 7 (int: 7) product: 12 (int: 12) overflow in: nothing
Example 2 · Input
2147483647 1
Expected output
sum: 2147483648 (int: -2147483648) product: 2147483647 (int: 2147483647) overflow in: sum
Hints
Hint 1
Compute the result again as a long: (long) a + b. If it differs from the int result, the int overflowed.
Hint 2
Math.addExact and Math.multiplyExact throw ArithmeticException on overflow, but comparing with long is enough here.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
long sum = (long) a + b;
long product = (long) a * b;
int intSum = a + b;
int intProduct = a * b;
System.out.println("sum: " + sum + " (int: " + intSum + ")");
System.out.println("product: " + product + " (int: " + intProduct + ")");
boolean s = sum != intSum;
boolean p = product != intProduct;
String which = s && p ? "sum, product" : s ? "sum" : p ? "product" : "nothing";
System.out.println("overflow in: " + which);
}
}