What is Math addExact(int x, int y) in Java?

The addExact() method is used to add two numbers of primitive integer datatype. As a result, the sum is also an integer value.

This method also returns an exception when the addition of two numbers exceeds the range of int.

Syntax


static int addExact(int x, int y)

Parameters

  • x: A 32-bit integer value is the first argument value.
  • y: A 32-bit integer value is the second argument value.

Return Value

sum: This method will return a 32-bit integer sum of two parameters x & y.

If the sum exceeds the maximum value of integer -2147483648 to 2147483647, it will raise the Arithmetic Exception, i.e., integer overflow.

Example

Case #1: In this example, x= 20 and y= 10, so the sum of these two numbers is 30. It works smoothly and prints the console Sum: 30. But what if the sum exceeds 32-bits?

Let’s consider Case #2.

Case #2: In this worst-case scenario, x= Integer.MAX_VALUE (x is assigned with a maximum possible value of integer) and y= 30. The sum will exceed 32-bit and it will throw ArithmeticException: integer overflow.

In Integer.MAX_VALUE, Integer is a wrapper class that wraps a value of the primitive type int in an object.

// main program
class EdPresso {
// main method
public static void main( String args[] ) {
// x contain 20 and y contain 10
int x = 20;
int y = 10;
// Sum will be 30
System.out.println("Sum: " + Math.addExact(x, y));
}
}

Free Resources