Open In App

Java Math subtractExact() Method

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The subtractExact() is a built-in function in Java provided by the Math class. This method returns the difference of the arguments. It throws an exception if the result overflows an int or long data type. As subtractExact() is static, so object creation is not required.

This method helps detect overflows when working with values near the limits of int or long.

Syntax of subtractExact() Method

int Math.subtractExact(int a, int b)

long Math.subtractExact(long x, long y)

  • Parameters:
    • a, x: The value from which another value is to be subtracted.
    • b, y: The value to subtract.
  • Returns: It returns the difference a - b or x - y, till when it causes an overflow.
  • Exception Throws: It throws an ArithmeticException if the result overflows the range of the data type.

Examples of Java Math subtractExact() Method

Example 1: In this example, we will see the basic usage of subtractExact() with int data type.

Java
// Java program to show how 
// subtractExact() works with int
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int a = 50;
        int b = 30;

        System.out.println(Math.subtractExact(a, b));  
    }
}

Output
20


Example 2: In this example, we will see the basic usage of subtractExact() with long data type.

Java
// Java program to demonstrate 
// subtractExact() with long
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        long x = 10000000000L;
        long y = 5000L;

        System.out.println(Math.subtractExact(x, y));  
    }
}

Output
9999995000


Example 3: In this example, we will see what happens in case of overflow.

Java
// Java program to demonstrate overflow with int
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int a = Integer.MIN_VALUE;
        int b = 1;

        System.out.println(Math.subtractExact(a, b));
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow

Explanation: Here in this example, the Integer.MIN_VALUE - 1 results below the int range. So, it throws an overflow exception.

Note: Similarly we can check for overflow with long values.

When Should We Use subtractExact() Method

  • We should use this method in financial or scientific calculations where exact values are important.
  • To catch overflow-related bugs during development and testing.

Practice Tags :

Similar Reads