Sum two large int/long and operation overflow in Java



Write a program that sums two large int/long and throws an ArithmeticException in case of operation overflow.

Java program to sum two large int/long

import java.util.function.BinaryOperator;

public class Main {

    public static void main(String[] args) {

        int x = Integer.MAX_VALUE;
        int y = Integer.MAX_VALUE;

        int z = x + y;
        System.out.println(x + " + " + y + " via '+' operator is: " + z);

        int zSum = Integer.sum(x, y);
        System.out.println(x + " + " + y + " via Integer.sum() is: " + zSum);

        // throw ArithmeticException
        int zExact = Math.addExact(x, y);
        System.out.println(x + " + " + y + " via Math.addExact() is: " + zExact);

        // throw ArithmeticException
        BinaryOperator<Integer> operator = Math::addExact;
        int zExactBo = operator.apply(x, y);
        System.out.println(x + " + " + y + " via BinaryOperator is: " + zExactBo);
    }
}

Output:

2147483647 + 2147483647 via '+' operator is: -2
2147483647 + 2147483647 via Integer.sum() is: -2
Exception in thread "main" java.lang.ArithmeticException: integer overflow
	at java.base/java.lang.Math.addExact(Math.java:827)
	at P26_SumTwoLargeIntsAndLongsOperationOverflow.src.modern.challenge.Main.main(Main.java:19)


Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments