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


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.


  • 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.


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.


import java.util.Scanner;

 * This example source code demonstrates the use of  
 * addExact() method of Math class

public class MathAddExactExample {

	public static void main(String[] args) {
		// Ask for user input
		System.out.print("Enter 1st value:");
		// use scanner to read the console input
		Scanner scan = new Scanner(;
		// Assign the 1st input to String variable
		String value1 = scan.nextLine();
		// ask for the second input
		System.out.print("Enter 2nd value:");
		// Assign the 2nd input to String variable
		String value2 = scan.nextLine();
		// close the scanner object
		// convert the values to int
		int intVal1 = Integer.parseInt(value1);
		int intVal2 = Integer.parseInt(value2);				
		// get the result of addExact method
		int result = Math.addExact(intVal1,intVal2);
		System.out.print("Result of the operation:"+result);


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