Home »
Java »
Java Programs
Java program to demonstrate the Math.addExact() method
Java example to demonstrate the Math.addExact() method.
Submitted by Nidhi, on May 17, 2022
Problem statement
In this program, we will create an integer number from the user using the Scanner class. Then we will use Math.addExact() method. The Math.addExact() method returns the addition of its arguments, throwing an exception if the result overflows.
Java program to demonstrate the Math.addExact() method
The source code to demonstrate the Math.addExact() method is given below. The given program is compiled and executed successfully.
// Java program to demonstrate the
// Math.floorDiv() method
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
System.out.print("Enter number1: ");
num1 = X.nextInt();
System.out.print("Enter number2: ");
num2 = X.nextInt();
System.out.print("Result: " + Math.floorDiv(num1, num2));
}
}
Output
Addition is: 2147483647
Exception: java.lang.ArithmeticException: integer overflow
Explanation
In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main that contains a main() method.
The main() method is the entry point for the program. And, created a variable num of integer type and then we used Math.addExact() method. It returns the addition of its arguments, throwing an exception if the result overflows.
Java Math Class Programs »