The java.lang.Math.subtractExact() is a built-in math function in java that returns the difference of the arguments. It throws an exception if the result overflows an int. As subtractExact(int a, int b) is static, so object creation is not required.
Syntax:
public static int subtractExact(int a, int b)
Parameters:
- a: the first value
- b: the second value to be subtracted from the first
Return Type: This method returns the difference between the arguments.
Exception: It throws ArithmeticException – if the result overflows an int
Example: To show the working of java.lang.Math.subtractExact() method.
java
// Java program to demonstrate working // of java.lang.Math.subtractExact() method import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
int a = 300 ;
int b = 200 ;
System.out.println(Math.subtractExact(a, b));
}
} |
Output
100
Example:
java
// Java program to demonstrate working // of java.lang.Math.subtractExact() method import java.lang.Math;
class Gfg2 {
// driver code
public static void main(String args[])
{
int x = Integer.MIN_VALUE;
int y = 10 ;
System.out.println(Math.subtractExact(x, y));
}
} |
Output:
Runtime Error: Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.lang.Math.subtractExact(Math.java:829) at Gfg2.main(File.java:13)
Example:
Java
class A {
// Main driver code
public static void main(String[] args)
{
int a = 5 ; // integer value 5
int b = 3 ; // integer value 3
int result = Math.subtractExact(a, b);
// Print statement
System.out.println( "The difference of " + a
+ " and " + b + " is " + result);
}
} |
Output
The difference of 5 and 3 is 2