Java Math subtractExact() Method

Java Math subtractExact() method

Java Math Class

Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc.
The java.lang.Math class contains various methods for performing basic numeric operations

Here, in the page we will discuss about the math subtractExact() Method in java.

Java Math subtractExact() Method :

The Math.subtractExact(int x, int y) method is a static method in the java.lang.Math class that returns the result of x – y, throwing an ArithmeticException if the result overflows an int. This method is equivalent to the following code: or we can say that returns the difference of the arguments, throwing an exception if the result overflows an int.
 
Note: The data type of both values should be either int or long.

Syntax  :

public static int subtractExact(int x,int y)
public static long subtractExact(long x,long y)

Example 1 :  

Run
public class Main {
    public static void main(String[] args) {
        int x = 100;
        int y = 50;
        int resultInt = Math.subtractExact(x, y);
        System.out.println(resultInt);

        long a = 200L;
        long b = 100L;
        long resultLong = Math.subtractExact(a, b);
        System.out.println(resultLong);
    }
}

Output :

50
100

Example 2:  

Run
public class Main {
    public static void main(String[] args) {
        try {
            int resultInt = Math.subtractExact(Integer.MAX_VALUE, 1);
            System.out.println(resultInt);
        } catch (ArithmeticException e) {
            System.out.println("The result overflowed an int");
        }

        try {
            long resultLong = Math.subtractExact(Long.MAX_VALUE, 1);
            System.out.println(resultLong);
        } catch (ArithmeticException e) {
            System.out.println("The result overflowed a long");
        }
    }
}

Output :

The result overflowed an int
The result overflowed a long

Note : The overflow depends upon the complier like on which  architecture they have been made .  

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription