How to check if integer multiplication will overflow in Java

2 Answers

0 votes
public class OverflowCheck {
    static boolean multiplyWillOverflow(int x, int y) {
	    return Integer.MAX_VALUE / x < y;
    }
 
    public static void main(String[] args) {
        int x = 3, y = 13727832;
        System.out.println(multiplyWillOverflow(x, y) ? "true" : "false");
 
        x = 1438839299; y = 3;
        System.out.println(multiplyWillOverflow(x, y) ? "true" : "false");
    }
}
 
 
 
/*
run:
  
false
true
  
*/

 



answered May 18, 2025 by avibootz
0 votes
public class OverflowCheck {
    public static void main(String[] args) {
        int a = 1438839299;
        int b = 3;

        try {
            int result = Math.multiplyExact(a, b);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle overflow exception
            System.err.println("Overflow occurred during multiplication: " + e.getMessage());
        }
    }
}

 
 
/*
run:
  
Overflow occurred during multiplication: integer overflow
  
*/

 



answered May 18, 2025 by avibootz
...