Java Math decrementExact() Method
The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long.
Syntax:
public static int decrementExact (int a)
Parameters:
The parameter ‘a’ represents the value to decrement.
Return Value:
The decrementExact () method returns the result after decrementing the value.
Throws:
The decrementExact () method throws:
ArithmeticException- if the result overflows an int or a long
Example 1:
public class JavaMathDecrementExactExample1 { public static void main(String[] args) { int a=90; //returns the result after decrementing the int value System.out.println("Decremented value : "+Math.decrementExact(a)); } }
Output:
Decremented value : 89
Example 2:
public class JavaMathDecrementExactExample2 { public static void main(String[] args) { //type cast the value Math.PI into int int a= (int) Math.PI; System.out.println("Cosine value for "+a+" = "+Math.decrementExact(a)); } }
Output:
Cosine value for 3 = 2
Example 3:
public class JavaMathDecrementExactExample3 { public static void main(String[] args) { //returns the result after decrementing the long value long x = Long.MAX_VALUE; System.out.println("Decremented value for "+x+": "+Math.decrementExact(x)); } }
Output:
Decremented value for 9223372036854775807: 9223372036854775806
Example 4:
public class JavaMathDecrementExactExample4 { public static void main(String[] args) { //returns an exception is the result overflows a long long x = Long.MIN_VALUE; System.out.println("Decremented value for "+x+": "+Math.decrementExact(x)); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.decrementExact(Math.java:960) at com.Tutorials And Examples.JavaMathDecrementExactExample4.main (JavaMathDecrementExactExample4.java:7)