Performing Precise Long Integer Addition with addExact() Method in Java

Rumman Ansari   Software Engineer   2024-07-04 04:20:55   6009  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

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

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(long x, long value) method of Math class
 */

public class MathAddExactLongExample {

	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 long
		long longVal1 = Long.parseLong(value1);
		long longVal2 = Long.parseLong(value2);

		// get the result of addExact method
		long result = Math.addExact(longVal1,longVal2);
		System.out.println("Result of the operation:"+result);
	}

}

output

Enter 1st value:123456789
Enter 2nd value:123456789
Result of the operation:246913578
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 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.