Java Math provides ‘decrementExact’ method, which is used to decremement the number by 1. It is available in below overloaded forms.
public static int decrementExact(int a)
Returns the argument decremented by one, throwing an ArithmeticException if the result overflows an int.
public static long decrementExact(long a)
Returns the argument decremented by one, throwing an ArithmeticException if the result overflows a long.
Find the below working application.
DecrementExactDemo.java
package com.sample.app;
public class DecrementExactDemo {
private static void decrementExact(int number) {
try {
System.out.printf("decrementExact(%d) is %d\n", number, Math.decrementExact(number));
} catch (ArithmeticException e) {
System.out.println("Error occurred while decremeting the number : " + number);
e.printStackTrace();
}
}
private static void decrementExact(long number) {
try {
System.out.printf("decrementExact(%d) is %d\n", number, Math.decrementExact(number));
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println();
}
}
public static void main(String[] args) {
int a = 10;
int b = Integer.MIN_VALUE;
decrementExact(a);
decrementExact(b);
System.out.println();
long c = 10l;
long d = Long.MIN_VALUE;
decrementExact(c);
decrementExact(d);
}
}
Output
decrementExact(10) is 9 Error occurred while decremeting the number : -2147483648 java.lang.ArithmeticException: integer overflow at java.lang.Math.decrementExact(Math.java:943) at com.sample.app.DecrementExactDemo.decrementExact(DecrementExactDemo.java:7) at com.sample.app.DecrementExactDemo.main(DecrementExactDemo.java:28) decrementExact(10) is 9 java.lang.ArithmeticException: long overflow at java.lang.Math.decrementExact(Math.java:960) at com.sample.app.DecrementExactDemo.decrementExact(DecrementExactDemo.java:16) at com.sample.app.DecrementExactDemo.main(DecrementExactDemo.java:36)
Previous Next Home
No comments:
Post a Comment