Java Math addExact()

The Java Math addExact() method adds the specified numbers and returns it.

The syntax of the addExact() method is:

Math.addExact(num1, num2)

Here, addExact() is a static method. Hence, we are accessing the method using the class name, Math.


addExact() Parameters

The addExact() method takes two parameters.

  • num1 - value that is added to num2
  • num2 - value that is added to num1

Note: The data type of both values should be either int or long.


addExact() Return Value

  • returns the sum of two values

Example 1: Java Math addExact()

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    int a = 24;
    int b = 33;

    // addExact() with int arguments
    System.out.println(Math.addExact(a, b));  // 57

    // create long variable
    long c = 12345678l;
    long d = 987654321l;

    // addExact() with long arguments
    System.out.println(Math.addExact(c, d));  // 999999999
  }
}

In the above example, we have used the Math.addExact() method with the int and long variables to calculate the sum.


The addExact() method throws an exception if the result of addition overflows the data type. That is, the result should be within the range of the data type of specified variables.

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create int variable
    // maximum int value
    int a = 2147483647;
    int b = 1;

    // addExact() with int arguments
    // throws exception
    System.out.println(Math.addExact(a, b));
  }
}

In the above example, the value of a is the maximum int value and the value of b is 1. When we add a and b,

  2147483647 + 1
=> 2147483648    // out of range of int type     

Hence, the addExact() method throws the integer overflow exception.


Recommended Tutorials