Java Math addExact(long x, long y) method
The java.lang.Math.addExact() is a built-in math function in java which returns the sum of its arguments.
It throws an exception if the result overflows a long.As addExact(long x, long y) is static, so object creation
is not required.
Syntax :
public static long addExact(long x, long y) Parameter : a : the first value b : the second value Return : This method returns the the sum of its arguments. Exception : It throws ArithmeticException - if the result overflows a long
Example :To show working of java.lang.Math.addExact() method.
// Java program to demonstrate working // of java.lang.Math.addExact() method import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { long x = 9999999999l; long y = 1l; System.out.println(Math.addExact(x, y)); } } |
chevron_right
filter_none
Output:
10000000000
// Java program to demonstrate working // of java.lang.Math.addExact() method import java.lang.Math; class Gfg2 { // driver code public static void main(String args[]) { long a = Long.MAX_VALUE; long b = 2l; System.out.println(Math.addExact(a, b)); } } |
chevron_right
filter_none
Output:
Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: long overflow
at java.lang.Math.addExact(Math.java:809)
at Gfg2.main(File.java:13)
Recommended Posts:
- Java Math subtractExact(long x, long y) method
- Java Math toIntExact(long value) Method
- Java Guava | LongMath.divide(long, long, RoundingMode) method with Examples
- Java Guava | LongMath.checkedAdd(long a, long b) method with Examples
- Java Guava | Longs.checkedSubtract(long a, long b) method with Examples
- Java Guava | Longs.indexOf(long[] array, long[] target) method with Examples
- Java Guava | Longs.indexOf(long[] array, long target) method with Examples
- Duration ofSeconds(long, long) method in Java with Examples
- Java Guava | mod(long x, long m) of LongMath Class with Examples
- Java Guava | mean(long x, long y) of LongMath Class with Examples
- Java Guava | gcd(long a, long b) of LongMath Class with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java lang.Long.builtcount() method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



