Java Math subtractExact() Method
The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long.
Syntax:
- public static int subtractExact (int x, int y)
- public static long subtractExact (long x, long y)
Parameters:
The parameters ‘x’ and ‘y’ represent the first and second number.
Return Value:
The subtractExact () method returns the result after subtraction of the specified arguments.
Throws:
The subtractExact () method throw:
ArithmeticException- if the result overflows int or long.
Example 1:
public class JavaMathSubtractExactExample1 { public static void main(String[] args) { int a=90; int b=10; //returns the result after subtracting the two int values System.out.println("Difference: "+Math.subtractExact(a,b)); } }
Output:
Difference: 80
Example 2:
public class JavaMathSubtractExactExample2 { public static void main(String[] args) { //return zero, if both the arguments are same int a=10; int b=10; System.out.println("Difference = "+Math.subtractExact(a,b)); } }
Output:
Difference = 0
Example 3:
public class JavaMathSubtractExactExample3 { public static void main(String[] args) { //returns an exception is the result overflows a long long x = Long.MAX_VALUE; long y= Long.MIN_VALUE; System.out.println("Difference : "+Math.subtractExact(x,y)); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.subtractExact(Math.java:849) at com.TutorialsAndExamples.JavaMathSubtractExactExample3.main(JavaMathSubtractExact Example3.java:8)