How to check if integer addition will overflow in Java

3 Answers

0 votes
public class OverflowCheck {

    public static boolean addingWillOverflow(int x, int y) {
        return ((x > 0) && (y > Integer.MAX_VALUE - x)) || ((x < 0) && (y < Integer.MIN_VALUE - x));
    }

    public static void main(String[] args) {
        int x = 38839299, y = 1372783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");

        x = 1438839299; y = 1972783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");
    }
}



/*
run:
 
false
true
 
*/

 



answered May 17, 2025 by avibootz
0 votes
public class OverflowCheck {

    public static boolean addingWillOverflow(Integer x, Integer y) {
        return ((x > 0) && (y > Integer.MAX_VALUE - x)) || ((x < 0) && (y < Integer.MIN_VALUE - x));
    }

    public static void main(String[] args) {
        Integer x = 39839299, y = 1472783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");

        x = 1338839299; y = 1872783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");
    }
}



/*
run:
 
false
true
 
*/

 



answered May 17, 2025 by avibootz
0 votes
import static java.lang.Math.addExact;
import static java.lang.Math.subtractExact;

public class OverflowCheck {

    public static boolean addingWillOverflow(Integer x, Integer y) {
        try {
            addExact(x, y);
            subtractExact(x, y);
            return false;
        } catch (ArithmeticException e) {
            return true;
        }
    }

    public static void main(String[] args) {
        Integer x = 39839299, y = 1472783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");

        x = 1338839299; y = 1872783642;
        System.out.println(addingWillOverflow(x, y) ? "true" : "false");
    }
}



/*
run:
 
false
true
 
*/

 



answered May 17, 2025 by avibootz

Related questions

2 answers 204 views
1 answer 275 views
1 answer 252 views
1 answer 261 views
1 answer 262 views
...