java.lang.Math addExact(int x, int y)

Description

On this document we will be showing a java example on how to use the addExact(int x, int y) method of Math Class. The addExact(int x, int y) returns the sum of its arguments, throwing an exception if the result overflows an int.

Notes:

  • the addExact() method will throw ArithmeticException if the result overflows an int.

 

Most of the methods of the Math class is static and the addExact() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. You can use the method in the format Math.addExact(int x, int y).

Method Syntax

public static int addExact(int x, int y)

Method Argument

Data Type Parameter Description
int x the first value
int y the second value

Method Returns

The addExact(int x, int y) method returns the result of adding the specified method argument x and y.

Compatibility

Requires Java 1.8 and up

Java Math addExact() Example

Below is a java code demonstrates the use of addExact() method of Math class. The example presented might be simple however it shows the behavior of the addExact() method.

The above java example source code demonstrates the use of addExact() method of Math class. We simply ask for two user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value, and the return data type is String thus we have used the Integer.parseInt() to transform it into int. We have to convert it first to int because the addExact(int x, int y) method accepts int method argument.

Sample Output

Below is the sample output when you run the above example.

java lang Math addExact(int x, int y) example output