Open In App

Java Math incrementExact() Method

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The incrementExact() is a built-in function in Java provided by the Math class, which returns the argument incremented by one. It throws an exception if the result overflows the specified datatype, either long or int, depending on which data type has been used on the method argument.

This method is helpful when we work with values near the maximum or minimum limits of integer types.

Syntax of incrementExact() Method

int Math.incrementExact(int num)

long Math.incrementExact(long num)

  • Parameter: num: The number we want to increment.
  • Returns: It returns the value num + 1, unless it causes an overflow.
  • Exception Throws: It throws an ArithmeticException if the increment overflows the data type range.

Examples of Java Math incrementExact() Method

Example 1: In this example, we will see the basic usage of incrementExact() method.

Java
// Java program to show how incrementExact() works
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int a = 12;
        int b = -3;

        System.out.println(Math.incrementExact(a));  
        System.out.println(Math.incrementExact(b));  
    }
}

Output
13
-2

Explanation: Here in this example, the values 12 and -3 are safely incremented by 1. Here no exception is thrown because they are within the valid range for integers.


Example 2: In this example, we will see what happens in the case of overflow.

Java
// Java program to demonstrate 
// overflow with incrementExact()
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        int max = Integer.MAX_VALUE;

        // This will throw ArithmeticException
        System.out.println(Math.incrementExact(max));
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow

Explanation: Here in this example, the value of Integer.MAX_VALUE is 2147483647. When we try to increment it goes beyond the int range, which throws an exception. This is useful to avoid silent overflow bugs.


When Should We Use incrementExact() Method?

  • We should use this method when we perform any arithmetic operations where overflow matters.
  • In financial or large calculations where silent overflow could cause major issues.
  • To catch bugs during development where values grow continuously.

Important Points:

  • It works with both int and long types.
  • It is safer than using num + 1 in financial or large calculations.

Practice Tags :

Similar Reads