Multiply two large int/long and operation overflow in Java



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

Java program to Multiply two large int/long and operation overflow

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);
        
        long zFull = Math.multiplyFull(x, y);       
        System.out.println(x + " * " + y + " via Math.multiplyFull() is: " + zFull);
                        
        // throw ArithmeticException
        int zExact = Math.multiplyExact(x, y);
        System.out.println(x + " * " + y + " via Math.multiplyExact() is: " + zExact);                
        
        // throw ArithmeticException
        BinaryOperator<Integer> operator = Math::multiplyExact;
        int zExactBo = operator.apply(x, y);
        System.out.println(x + " * " + y + " via BinaryOperator is: " + zExactBo);                
    }

}

Output:

2147483647 * 2147483647 via '*' operator is: 1
2147483647 * 2147483647 via Math.multiplyFull() is: 4611686014132420609
Exception in thread "main" java.lang.ArithmeticException: integer overflow
	at java.base/java.lang.Math.multiplyExact(Math.java:908)
	at P37_ProductTwoLargeIntAndLongAndOperationOverflow.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