Java Math incrementExact(int x) method
Last Updated :
01 May, 2018
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.
import java.lang.Math;
class Gfg1 {
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
import java.lang.Math;
class Gfg2 {
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)
Share your thoughts in the comments
Please Login to comment...