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

Description

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

Notes:

  • the addExact() method will throw ArithmeticException if the result overflows a long.
  • In order to find what is the maximum value, you can use the Long.MAX_VALUE.

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(long x, long y).

Method Syntax

public static long addExact(long x, long y)

Method Argument

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

Method Returns

The addExact(long x, long y) method returns long which corresponds to 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 Long.parseLong to transform it into long. We have to convert it first to long because the addExact(long x, long y) method accepts long method argument.

Sample Output

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

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