English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Control Flow

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)/)

Java Reader/Writer

Java other topics

Java Math addExact() method usage and example

Java Math Mathematical Methods

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

The syntax of the addExact() method is:

Math.addExact(num1, num2)

Note: addExact() is a static method. Therefore, we can use the class name Math to access this method.

addExact() parameter

  • num1 / num2 - To return the first and second values whose sum is to be calculated

Note: The data types of these two values should be int or long.

addExact() return value

  • Return the sum of two values

Example1: Java Math addExact()

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable
    int a = ; 24;
    int b = ; 33;
    // addExact() with int parameter
    System.out.println(Math.addExact(a, b));  // 57
    //Create a long variable
    long c = ; 12345678l;
    long d = ; 987654321l;
    //addExact() with long parameter
    System.out.println(Math.addExact(c, d));  // 999999999
  }
}

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

Example2: Math addExact() result overflow throws exception

If the result of the addition overflows the data type, the addExact() method will throw an exception. That is, the result should be within the range of the specified variable's data type.

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable.
    //Maximum int value
    int a = ; 2147483647;
    int b = ; 1;
    //addExact() with int parameters.
    //Throws an 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 is1When we add a and b,

  2147483647 + 1
=> 2147483648    // Out of the range of int type

Therefore, the addExact() method triggers an integer overflow exception.

Recommended Tutorials

Java Math Mathematical Methods