Java Math incrementExact() Method
The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long.
Syntax:
- public static int incrementExact (int a)
- public static int incrementExact (long a)
Parameters:
The parameters ‘f1’ and ‘f2’ represent the dividend and the divisor.
Return Value:
The incrementExact () method returns the result after incrementing the argument by one.
Throws:
The incrementExact () method throws:
ArithmeticException – if the result overflows an int or long
Example 1:
public class JavaMathIncrementExactExample1 {
public static void main(String[] args) {
int a=90;
//returns the result after incrementing the int value
System.out.println("Incremented value : "+Math.incrementExact(a));
}
}
Output:
Incremented value : 91
Example 2:
public class JavaMathIncrementExactExample2 {
public static void main(String[] args) {
//type cast the value Math.PI into int
int a= (int) Math.PI;
System.out.println("Incremented value for
"+Math.PI+" = "+Math.incrementExact(a));
}
}
Output:
Incremented value for 3.141592653589793 = 4
Example 3:
public class JavaMathIncrementExactExample3 {
public static void main(String[] args) {
//returns an exception is the result overflows a long
long x = Long.MAX_VALUE;
System.out.println("Incremented value for "+x+":
"+Math.incrementExact(x));
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.incrementExact(Math.java:926) at com.TutorialsAndExamples.JavaMathIncrementExactExample3.main (JavaMathIncrementExactExample3.java:7)
Example 4:
public class JavaMathIncrementExactExample4 {
public static void main(String[] args) {
//returns the result after incrementing the long value
long x = Long.MIN_VALUE;
System.out.println("Incremented value for "+x+":
"+Math.incrementExact(x));
}
}
Output:
Incremented value for -9223372036854775808: -9223372036854775807
