Close

Java - Math.decrementExact() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Methods:

public static int decrementExact(int a)

Returns the argument decremented by one, throwing an exception if the result overflows an int.



public static long decrementExact(long a)

Returns the argument decremented by one, throwing an exception if the result overflows a long


Examples


package com.logicbig.example.math;

public class DecrementExactExample {

public static void main(String... args) {
findDecrementExact(130);
findDecrementExact(255);
findDecrementExact(-22);
findDecrementExact(0);
findDecrementExact(Integer.MAX_VALUE);

}

private static void findDecrementExact(int x) {
int result = Math.decrementExact(x);
System.out.printf("Decrement by one value of %s = %d%n", x, result);
}
}

Output

Decrement by one value of  130 = 129
Decrement by one value of 255 = 254
Decrement by one value of -22 = -23
Decrement by one value of 0 = -1
Decrement by one value of 2147483647 = 2147483646




package com.logicbig.example.math;

public class DecrementExactExample2 {

public static void main(String... args) {
long x = Long.MIN_VALUE + 3;
for (int y = 1; y <= 4; y++) {
System.out.printf("%37s - 1 = %s%n", x, x - 1);
try {
x = Math.decrementExact(x);
System.out.printf("Math.decrementExact(%s) = %s%n", x, x);
} catch (Exception e) {
System.out.println("error: " + e);
}

System.out.println("-----------");
}
}

}

Output

                 -9223372036854775805 - 1 = -9223372036854775806
Math.decrementExact(-9223372036854775806) = -9223372036854775806
-----------
-9223372036854775806 - 1 = -9223372036854775807
Math.decrementExact(-9223372036854775807) = -9223372036854775807
-----------
-9223372036854775807 - 1 = -9223372036854775808
Math.decrementExact(-9223372036854775808) = -9223372036854775808
-----------
-9223372036854775808 - 1 = 9223372036854775807
error: java.lang.ArithmeticException: long overflow
-----------




See Also