Close

Java - Math.subtractExact() Examples

Java Java API 


Class:

java.lang.Math

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

Methods:

public static int subtractExact(int x,
                                int y)

Returns the difference of the arguments, throwing an exception if the result overflows an int.

Parameters:
x - the first value
y - the second value to subtract from the first
Returns:
the result
Throws:
java.lang.ArithmeticException,ArithmeticException - if the result overflows an int
Since:
1.8



public static long subtractExact(long x,
                                 long y)

Returns the difference of the arguments, throwing an exception if the result overflows a long.

Parameters:
x - the first value
y - the second value to subtract from the first
Returns:
the result
Throws:
java.lang.ArithmeticException,ArithmeticException - if the result overflows a long
Since:
1.8


Examples


package com.logicbig.example.math;

public class SubtractExactExample {

public static void main(String... args) {
int x = 3500;
System.out.println("First Integer: " + x);
int y = 2000;
System.out.println("Second Integer: " + y);
int result = Math.subtractExact(x, y);
System.out.printf("Math.subtractExact(%s,%s): ", x, y, result);
}
}

Output

First Integer: 3500
Second Integer: 2000
Math.subtractExact(3500,2000):




package com.logicbig.example.math;

public class SubtractExactExample2 {

public static void main(String... args) {
long x = Long.MIN_VALUE + 3;
for (long y = 1; y <= 5; y++) {
System.out.println("-----------");
System.out.println("Result without Math.subtractExact: ");
System.out.printf("%s - %s = %s%n", x, y, x - y);
System.out.println("Result with Math.subtractExact: ");
try {
x = Math.subtractExact(x, y);
} catch (ArithmeticException e) {
System.out.println("error: " + e);
continue;
}
System.out.println(x);
}
}
}

Output

-----------
Result without Math.subtractExact:
-9223372036854775805 - 1 = -9223372036854775806
Result with Math.subtractExact:
-9223372036854775806
-----------
Result without Math.subtractExact:
-9223372036854775806 - 2 = -9223372036854775808
Result with Math.subtractExact:
-9223372036854775808
-----------
Result without Math.subtractExact:
-9223372036854775808 - 3 = 9223372036854775805
Result with Math.subtractExact:
error: java.lang.ArithmeticException: long overflow
-----------
Result without Math.subtractExact:
-9223372036854775808 - 4 = 9223372036854775804
Result with Math.subtractExact:
error: java.lang.ArithmeticException: long overflow
-----------
Result without Math.subtractExact:
-9223372036854775808 - 5 = 9223372036854775803
Result with Math.subtractExact:
error: java.lang.ArithmeticException: long overflow




See Also