What is Math.subtractExact() in Java?
The subtractExact method takes two arguments and returns the difference between them. The arguments will be either int or long.
subtractExact is a
Math class.
Syntax
public static long subtractExact(long a, long b);
public static int subtractExact(int a, int b);
Arguments
-
a: First value (int/long). -
b: Second value, which will be subtracted from first value (int/long).
Return value
This method returns the difference between a and b.
The subtractExact method is equivalent to:
argument1 - argument2
Code
Example 1
import java.lang.Math;class SubtractExactTest {public static void main(String cmdArgs[]) {int a = 20;int b = 10;int diff = Math.subtractExact(a, b);System.out.print("The difference of "+ a + " and " + b + " is ");System.out.println(diff);long la = 100l;long lb = 50l;long ldiff = Math.subtractExact(la, lb);System.out.print("The difference of "+ la + " and " + lb + " is ");System.out.println(ldiff);}}
Explanation 1
In the code above:
-
We created four variables,
aandb, of theintandla, andlbof thelongtype. -
We called the
Math.subtractExactmethod withaandbas arguments. This will return the difference ofaandbas result. -
Again, we called the
Math.subtractExactmethod withlaandlbas arguments. This will return the sum oflaandlbas a result.
The subtractExact method will throw ArithmeticException if:
-
the arguments are
intand thedifferenceoverflows theintvalue. -
the arguments are
longand thedifferenceoverflows thelongvalue.
Example 2
Consider if the two arguments are int. The ArithmeticException will be thrown if the difference of the two int arguments is less than the minimum value or greater than the maximum value that the int type can hold.
import java.lang.Math;class SubtractExactTest {public static void main(String cmdArgs[]) {try{int a = Integer.MIN_VALUE;int b = 1;int sum = Math.subtractExact(a, b);}catch(Exception e){System.out.println(e);}}}
Explanation 2
In the code above, we have created two variables, a and b, of the int type. We assigned the minimum value an integer can hold to the variable a, and 1 to the variable b.
When we call the subtractExact method with a and b as arguments, we will get ArithmeticException because the difference of a and b is less than the value an integer can hold.