Java Math decrementExact() method


The java.strictmath.lang.decrementExact() is a built-in function in java which returns the argument decremented by one, throwing an exception if the result overflows the specified datatype either long or int depending on which data type has been used on the method argument. Since this is decrement, the only scenario that we will be hitting an exception if the result is less than the minimum value. The minimum value can be derived from Long.MIN_VALUE or Integer.MIN_VALUE.

Syntax:

int decrementExact(int num)
long decrementExact(long num)

Parameter: The function accepts one mandatory parameter as shown above and described below:
num – The parameter specifies the number which has to be decremented.

Return Value: The function returns the argument decremented by one, throwing an exception if the result overflows the specified datatype either long or int depending on which data type has been used on the method argument.

Examples:



Input : 12
Output : 11

Input : -3 
Output : -4

Program 1: Program to demonstrate the working of function

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.decrementExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        int y = 12;
        System.out.println(Math.decrementExact(y));
  
        int x = -3;
        System.out.println(Math.decrementExact(x));
    }
}

chevron_right


Output:

11
-4

Program 2: Program to demonstrate the overflow in function

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate overflow
// of java.lang.Math.incrementExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        int y = Integer.MIN_VALUE;
        System.out.println(Math.decrementExact(y));
    }
}

chevron_right


Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.decrementExact(Math.java:943)
    at Gfg1.main(File.java:12)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.