Ensuring Exact Addition with addExact() Method in Java: A Complete Guide

Rumman Ansari   Software Engineer   2024-07-04 04:20:25   6331  Share
Subject Syllabus DetailsSubject Details 1 Program
☰ TContent
☰Fullscreen

Table of Content:

Description

On this tutorial, 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

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(System.in);

		// 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
		scan.close();

		// 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.println("Result of the operation:"+result);
	}

}

output

Enter 1st value:12
Enter 2nd value:13
Result of the operation:25
Press any key to continue . . .

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.