Home » Java Math.addExact() Method with Examples

Java Math.addExact() Method with Examples

by Online Tutorials Library

Java Math.addExact() method

The java.lang.Math.addExact() returns the sum of its arguments. It will throw an exception if the result overflows either int or long.

Syntax

Parameter

Return

  • If one of the arguments is Integer.MAX_VALUE or Long.MAX_VALUE, it will throw an ArithmeticException.

Example 1

Test it Now

Output:

1206  

Example 2

Test it Now

Output:

-738  

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow  at java.lang.Math.addExact(Math.java:790)  at AddExactExample3.main(AddExactExample3.java:8)  

Example 4

Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: long overflow  at java.lang.Math.addExact(Math.java:809)  at AddExactExample4.main(AddExactExample4.java:8)  

Next TopicJava Math

You may also like