StrictMath.toIntExact() in Java

StrictMath.toIntExact(): This method is available in java.lang.StrictMath class of Java.

Syntax:

int java.lang.StrictMath.toIntExact(long value)

This method takes one argument of type long as its parameter. This method returns the value of the long argument, throwing an exception if the value overflows an int.

Parameters: One parameter is required for this method.

value: the long value.

Returns: the argument as an int.

Throws:

ArithmeticException - if the argument overflows an int.

Approach 1: When no exceptions.

Java

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

        long value = 118819;
        System.out.println(StrictMath.toIntExact(value));
    }
}

Output:

118819


Approach 2: ArithmeticException 

Java

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

        long value = Long.MAX_VALUE;
        System.out.println(StrictMath.toIntExact(value));
    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.toIntExact(Math.java:1080) at java.base/java.lang.StrictMath.toIntExact(StrictMath.java:938)


No comments:

Post a Comment