Java Math addexact() Function

addExact Function

Java Math Class

Java Math class provides several basic and advance methods to perform different operations on math calculations like max(), min(), sin(), round(), ceil(), floor(), addexact() etc.
The java.lang.Math class contains various methods for performing basic numeric operations

Here, in the page we will discuss about the addexact() Method in java.

Java addexact() Function :

Java Collection contains Math class and The class Math contains methods for performing basic and advance numeric operations such as the exponential, logarithm, square root, and trigonometric functions.
The Java addexact() Function add two values and returns the addition of the two given numbers.
The Given two numbers should be of same data type and the result should be within the range of the data type of specified variables. .

Syntax:

Math.addexact(number1,number2);

Definition of Parameters:

Return Type :

Exceptions :

clear() Function in ArrayList

clone() Function in ArrayList

add() Function in ArrayList

addall() Function in ArrayList

Example :

Run
import java.util.*;

public class Main{
    public static void main(String[] args){
        // Initializing Integer Values
        int a = 10;
        int b = 20;
        
        int add = Math.addExact(a,b);
        
        // Printing addition of two numbers
        System.out.println("Addition of Given two Numbers : " + add);
        
    }
}
Output:

Addition of Given two Numbers : 30

In the above Example, We had taken two integer values and stores its sum in an integer variable with the help of AddExact Function. 

Example for Out of Range Number:

Run
import java.util.*;

public class Main{
    public static void main(String[] args){
        // Initializing
        int a = 2147483648;
        int b = 1;
        
        int add = Math.addExact(a,b);
        
        // Printing addition of two numbers
        System.out.println("Addition of Given two Numbers : " + add);
        
    }
}
Output:

/tmp/0j0UVr63Kz/Main.java:6: error: integer number too large
        int a = 2147483648;

In the above Example, We had taken the max value of an integer data type and adding another number to it which gives Arithmetic Exception.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription