Java Math subtractExact()

The syntax of the subtractExact() method is:

Math.subtractExact(num1, num2)

Here, subtractExact() is a static method. Hence, we are accessing the method using the class name, Math.


subtractExact() Parameters

The subtractExact() method takes two parameters.

  • num1 - value from which num2 is subtracted
  • num2 - value which is subtracted from num1

Note: The data type of both values should be either int or long.


subtractExact() Return Value

  • returns the difference between num1 and num2

Example 1: Java Math.subtractExact()

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    int a = 54;
    int b = 30;

    // subtractExact() with int arguments
    System.out.println(Math.subtractExact(a, b));  // 24

    // create long variable
    long c = 72345678l;
    long d = 17654321l;

    // subtractExact() with long arguments
    System.out.println(Math.subtractExact(c, d));  // 54691357
  }
}

In the above example, we have used the Math.subtractExact() method with the int and long variables to calculate the difference.


Example 2: Math.subtractExact() Throws Exception

The method subtractExact() throws an exception if the result of the difference overflows the data type. That is, the result should be within the range of the data type of specified variables.

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    // maximum int value
    int a = 2147483647;
    int b = -1;

    // subtractExact() with int arguments
    // throws exception
    System.out.println(Math.subtractExact(a, b));
  }
}

In the above example, the value of a is the maximum int value and the value of b is -1. When we subtract a and b,

  2147483647 - (-1)
=> 2147483647 + 1
=> 2147483648      // out of range of int type

Hence, the subtractExact() method throws the integer overflow exception.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges