StrictMath.addExact(long, long): This method is available in java.lang.StrictMath class of Java.
Syntax:
long java.lang.StrictMath.addExact(long x, long y)
This method takes two arguments of type long as its parameters. This method returns the sum of its arguments, throwing an exception if the result overflows a long.
Parameters: Two parameters are required for this method.
x: the first value.
y: the second value.
Returns: the result
Throws:
ArithmeticException - if the result overflows a long.
Approach 1: When no exceptions.
Java
public class StrictMathaddExactlong {public static void main(String[] args) {long x = 1899199191, y = 1999199919;System.out.println(StrictMath.addExact(x, y));}}
Output:
3898399110
Approach 2: ArithmeticException
Java
public class StrictMathaddExactlong {public static void main(String[] args) {long x = 1899199191, y = Long.MAX_VALUE;System.out.println(StrictMath.addExact(x, y));}}
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.base/java.lang.Math.addExact(Math.java:848) at java.base/java.lang.StrictMath.addExact(StrictMath.java:759)
No comments:
Post a Comment