Java Math incrementExact(int x) method

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
    }
}

chevron_right


Output:

1
2
3
4
5
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


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)


My Personal Notes arrow_drop_up

Welcome to Wenzkaba Planet

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.