Java Math decrementExact()

The syntax of the decrementExact() method is:

Math.decrementExact(num)

Here, decrementExact() is a static method. Hence, we are accessing the method using the class name, Math.


decrementExact() Parameters

The decrementExact() method takes a single parameter.

  • num - argument from which 1 is subtracted

Note: The data type of the argument should be either int or long.


decrementExact() Return Value

  • returns the value after subtracting 1 from the argument

Example 1: Java Math.decrementExact()

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

    // create a int variable
    int a = 65;

    // decrementExact() with the int argument
    System.out.println(Math.decrementExact(a));  // 64

    // create a long variable
    long c = 52336L;

    // decrementExact() with the long argument
    System.out.println(Math.decrementExact(c));  // 52335
  }
}

In the above example, we have used the Math.decrementExact() method with the int and long variables to subtract 1 from the respective variables.


Example 2: Math.decrementExact() Throws Exception

The decrementExact() method throws an exception if the result of the subtraction overflows the data type. That is, the result should be within the range of the data type of specified variables.

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

    // create a int variable
    // minimum int value
    int a = -2147483648;

    // decrementExact() with the int argument
    // throws exception
    System.out.println(Math.decrementExact(a));
  }
}

In the above example, the value of a is the minimum int value. Here, the decrementExact() method subtracts 1 from a.

   a - 1  
=> -2147483648 - 1
=> -2147483649    // out of range of int type     

Hence, the decrementExact() method throws the integer overflow exception.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges