Open In App

Java Math incrementExact(int x) method

Last Updated : 01 May, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

The java.lang.Math.incrementExact() is a built-in math function in java which returns the argument incremented by one.It throws an exception if the result overflows an int.As incrementExact(int x) is static, so object creation is not required.

Syntax :

public static int incrementExact(int x)
Parameter :
x : the value to be incremented
Return :
This method returns the argument incremented by one.
Exception :
It throws ArithmeticException - if the result overflows an int

Example : To show working of java.lang.Math.incrementExact() method.




// Java program to demonstrate working
// of java.lang.Math.incrementExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
        int a = 0;
  
        for (int i = 0; i < 5; i++) {
            a = Math.incrementExact(a);
            System.out.println(a);
        }
    }
}


Output:

1
2
3
4
5




// Java program to demonstrate working
// of java.lang.Math.incrementExact() method
import java.lang.Math;
  
class Gfg2 {
  
    // driver code
    public static void main(String args[])
    {
        int x = Integer.MAX_VALUE;
  
        System.out.println(Math.incrementExact(x));
    }
}


Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.incrementExact(Math.java:909)
    at Gfg2.main(File.java:13)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads