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()

class Main {
  public static void main(String[] args) {

    // create a int variable
    int a = 65;

    // incrementExact() with the int argument
    System.out.println(Math.incrementExact(a));  // 66

    // create a long variable
    long b = 52336L;

    // incrementExact() with the long argument
    System.out.println(Math.incrementExact(b));  // 52337
  }
}

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.

class Main {
  public static void main(String[] args) {

    // create a int variable
    // maximum int value
    int a = 2147483647;

    // incrementExact() with the int argument
    // throws exception
    System.out.println(Math.incrementExact(a));
  }
}

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.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges