Skip to content
Related Articles

Related Articles

Java Math subtractExact(long x, long y) method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 27 Apr, 2018
View Discussion
Improve Article
Save Article

The java.lang.Math.subtractExact() is a built-in math function in java which returns the difference of the
arguments.It throws an exception if the result overflows a long.As subtractExact(long x, long y) is static,
so object creation is not required.

Syntax :

public static long subtractExact(long x, long y)
Parameter :
 x : the first value
 y : the second value to be subtracted from the first
Return :
This method returns the difference of the arguments.
Exception :
It throws ArithmeticException - if the result overflows a long.

Example :To show working of java.lang.Math.subtractExact() method.




// 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[])
    {
        long x = 11111111111l;
        long y = 999l;
  
        System.out.println(Math.subtractExact(x, y));
    }
}

Output:

11111110112




// 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[])
    {
        long a = Long.MIN_VALUE;
        long b = 1;
  
        System.out.println(Math.subtractExact(a, b));
    }
}

Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: long overflow
    at java.lang.Math.subtractExact(Math.java:849)
    at Gfg2.main(File.java:13)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!