StrictMath.incrementExact(int) in Java

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

Syntax:

int java.lang.StrictMath.incrementExact(int a)

This method takes one argument of type int as its parameter. This method returns the argument incremented by one,throwing an exception if the result overflows an int. The overflow only occurs for the maximum value.

Parameters: One parameter is required for this method.

a:  the value to increment.

Returns: the result.

Throws:

ArithmeticException - if the result overflows an int.

Approach 1: When no exceptions.

Java

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

        int a = 1991;
        System.out.println(StrictMath.incrementExact(a));
    }
}

Output:

1992


Approach 2: ArithmeticException 

Java

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

        int a = Integer.MAX_VALUE;
        System.out.println(StrictMath.incrementExact(a));
    }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.incrementExact(Math.java:968) at java.base/java.lang.StrictMath.incrementExact(StrictMath.java:849)


No comments:

Post a Comment