StrictMath.subtractExact(int, int): This method is available in java.lang.StrictMath class of Java.
Syntax:
int java.lang.StrictMath.subtractExact(int x, int y)
This method takes two arguments of type int as its parameters. This method returns the difference of the arguments, throwing an exception if the result overflows an int.
Parameters: Two parameters are required for this method.
x: the first value.
y: the second value to subtract from the first.
Returns: the result.
Throws:
ArithmeticException - if the result overflows an int.
Approach 1: When no exceptions.
Java
public class StrictMathsubtractExact {public static void main(String[] args) {int x = 1919, y = 19;System.out.println(StrictMath.subtractExact(x, y));}}
Output:
1900
Approach 2: ArithmeticException
Java
public class StrictMathsubtractExact {public static void main(String[] args) {int x = Integer.MIN_VALUE, y = 19;System.out.println(StrictMath.subtractExact(x, y));}}
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.subtractExact(Math.java:869) at java.base/java.lang.StrictMath.subtractExact(StrictMath.java:774)
StrictMath.subtractExact(long, long)
No comments:
Post a Comment