Thursday, January 29, 2026
HomeLanguagesJavaJava Math addExact(int a, int b) method

Java Math addExact(int a, int b) 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 an int.As addExact(int a, int b) is static, so object creation
is not required.

Syntax :

public static int addExact(int a, int b)
Parameter :
 a : the first value
 b : the second value
Return :
This method returns the sum of its arguments.
Exception :
It throws ArithmeticException - if the result overflows an int

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[])
    {
        int a = 100;
        int b = 200;
  
        System.out.println(Math.addExact(a, b));
    }
}


Output:

300




// 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[])
    {
        int x = Integer.MAX_VALUE;
        int y = 200;
  
        System.out.println(Math.addExact(x, y));
    }
}


Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.addExact(Math.java:790)
    at Gfg2.main(File.java:13)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6848 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6916 POSTS0 COMMENTS