Related Articles

Related Articles

Java Math addExact(long x, long y) method
  • Last Updated : 26 Apr, 2018

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

10000000000
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


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)

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :