StrictMath.addExact(int , int) in Java

StrictMath.addExact(int , int): This method is available in java.lang.StrictMath class of Java.

Syntax:

int java.lang.StrictMath.addExact(int x, int y)

This method takes two arguments of type int as its parameters. This method returns the sum of its arguments,throwing an exception if the result overflows an int.

Parameters: Two parameters are required for this method.

x: the first value.

y: the second value.

Returns: the result.

Throws:

ArithmeticException - if the result overflows an int.

Approach 1: When no exceptions.

Java

public class StrictMathaddExactint {
    public static void main(String[] args) {

        int x = 10, y = 12;
        System.out.println(StrictMath.addExact(x, y));
    }
}

Output:

22


Approach 2: ArithmeticException 

Java

public class StrictMathaddExactint {
    public static void main(String[] args) {

        int x = 999999999, y = 2147483647;
        System.out.println(StrictMath.addExact(x, y));

    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.addExact(Math.java:828) at java.base/java.lang.StrictMath.addExact(StrictMath.java:744)


No comments:

Post a Comment