What is Math.decrementExact() in Java?
The decrementExact method in Java decrements the value passed as an argument by 1, and then returns the decremented value. The value stored in the passed variable is unchanged.
The arguments will be either int or long. decrementExact is a static method present in the Math class.
Syntax
public static long decrementExact(long a);
public static int decrementExact(int a);
Arguments
a: Value to decrement (int/long).
Return value
This function returns the decremented value of a, i.e, a-1.
Example
import java.lang.Math;class DecrementExact {public static void main(String cmdArgs[]) {int a = 10;int decrementedValue = Math.decrementExact(a);System.out.print("The decreamented value of "+ a + " is ");System.out.println(decrementedValue);long la = 100000000l;long lDecrementedValue = Math.decrementExact(la);System.out.print("The decreamented value of "+ la + " is ");System.out.println(lDecrementedValue);}}
In the code above:
-
We created two variables,
aof theinttype andlaof thelongtype. -
We called the
Math.decrementExactmethod withaas arguments. This will return the decrement of the value ofaby 1. In our case, the value ofa=10, sodecrementExactwill return9. The value ofaremains unchanged as10. -
Again, we called the
Math.decrementExactmethod withlaas an argument. This will return the decrement of the value oflaby1. In our case, the value ofla= 100000000, sodecrementExactwill return99999999.
The decrementExact method will throw an ArithmeticException if:
-
The argument is
intand thedecrementof the argument overflows theintvalue. -
The argument is
longand thedecrementof the argument overflows thelongvalue.
Example
For example, consider if the argument is int. The ArithmeticException will be thrown if the decrement of the int argument is less than the minimum value or greater than the maximum value that the int type can hold.
import java.lang.Math;class DerementExactTest {public static void main(String cmdArgs[]) {try{int a = Integer.MIN_VALUE;int decrementedVal = Math.decrementExact(a);}catch(Exception e){System.out.println(e);}}}
In the code above, we created a variable, a of the int type. We assigned the minimum value an integer can hold to the variable a.
When we call the decrementExact method with a as an argument, we will get ArithmeticException. This is because when we decrement the value of a, the value will be less than the minimum value an integer can hold.