Senior
Refine the method so that it returns an error upon overflow. Demonstrate with an example of adding two numbers.
sobes.tech AI
Answer from AI
In Java, to check for overflow when adding integers, you can use methods from the Math class, such as Math.addExact(), which throws an ArithmeticException on overflow. If you want to implement it yourself, you can check for overflow like this:
public class SafeMath {
public static int add(int a, int b) {
long result = (long) a + (long) b;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return (int) result;
}
public static void main(String[] args) {
try {
int sum = add(Integer.MAX_VALUE, 1);
System.out.println("Sum: " + sum);
} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
In this example, attempting to add Integer.MAX_VALUE and 1 will cause the method to throw an overflow exception with an error message.