![]() |
VOOZH | about |
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.
int Math.incrementExact(int num)
long Math.incrementExact(long num)
Example 1: In this example, we will see the basic usage of incrementExact() method.
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.
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflowExplanation: 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.
Important Points: