Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Math subtractExact(int a , int b) method

  • Difficulty Level : Basic
  • Last Updated : 19 Apr, 2018

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 an int.As subtractExact(int a, int b) is static, so
object creation is not required.

Syntax :

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

public static int subtractExact(int a, int b)
Parameter :
 a : the first value
 b : 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 an int

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[])
    {
        int a = 300;
        int b = 200;
  
        System.out.println(Math.subtractExact(a, b));
    }
}

Output:

100




// 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[])
    {
        int x = Integer.MIN_VALUE;
        int y = 10;
  
        System.out.println(Math.subtractExact(x, y));
    }
}

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!