Open In App

Java Math decrementExact() method

Last Updated : 19 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 

Java




// 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));
    }
}


Output: 

11
-4

Program 2: Program to demonstrate the overflow in the function  

Java




// Java program to demonstrate overflow
// of java.lang.Math.decrementExact() 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));
    }
}


Output: 

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

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads