Java Math incrementExact()

The syntax of the incrementExact() method is:

Math.incrementExact(num)

Here, incrementExact() is a static method. Hence, we are accessing the method using the class name, Math.


incrementExact() Parameters

The incrementExact() method takes a single parameter.

  • num - argument on which 1 is added

Note: The data type of the argument should be either int or long.


incrementExact() Return Value

  • returns the value after adding 1 to the argument

Example 1: Java Math.incrementExact()

In the above example, we have used the Math.incrementExact() method with the int and long variables to add 1 to the respective variables.


Example 2: Math.incrementExact() Throws Exception

The incrementExact() method throws an exception if the result of the addition overflows the data type. That is, the result should be within the range of the data type of specified variables.

In the above example, the value of a is the maximum int value. Here, the incrementExact() method adds 1 to a.

   a + 1  
=> 2147483647 + 1
=> 2147483648    // out of range of int type     

Hence, the incrementExact() method throws the integer overflow exception.


Recommended Tutorials