Close

Java - Math.incrementExact() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Methods:

public static int incrementExact(int a)

Returns the argument incremented by one, throwing an exception if the result overflows an int.

Since: 1.8



public static long incrementExact(long a)

Returns the argument incremented by one, throwing an exception if the result overflows a long.

Since: 1.8


Examples


package com.logicbig.example.math;

public class IncrementExactExample {

public static void main(String... args) {
findIncrementExact(41);
findIncrementExact(357);
findIncrementExact(-11);
findIncrementExact(0);
findIncrementExact(Integer.MIN_VALUE);
}

private static void findIncrementExact(int x) {
int result = Math.incrementExact(x);
System.out.printf("Increment by one value of %s = %d%n", x, result);
}
}

Output

Increment by one value of  41 = 42
Increment by one value of 357 = 358
Increment by one value of -11 = -10
Increment by one value of 0 = 1
Increment by one value of -2147483648 = -2147483647




package com.logicbig.example.math;

public class IncrementExactExample2 {

public static void main(String... args) {
long x = Long.MAX_VALUE - 3;
for (int y = 1; y <= 4; y++) {
System.out.println("-----------");
System.out.println("Result without Math.incrementExact: ");
System.out.printf("%s + 1 = %s%n", x, x + 1);
System.out.println("Result with Math.incrementExact: ");
try {
x = Math.incrementExact(x);
} catch (ArithmeticException e) {
System.out.println("error: " + e);
continue;
}
System.out.println(x);
}
}
}

Output

-----------
Result without Math.incrementExact:
9223372036854775804 + 1 = 9223372036854775805
Result with Math.incrementExact:
9223372036854775805
-----------
Result without Math.incrementExact:
9223372036854775805 + 1 = 9223372036854775806
Result with Math.incrementExact:
9223372036854775806
-----------
Result without Math.incrementExact:
9223372036854775806 + 1 = 9223372036854775807
Result with Math.incrementExact:
9223372036854775807
-----------
Result without Math.incrementExact:
9223372036854775807 + 1 = -9223372036854775808
Result with Math.incrementExact:
error: java.lang.ArithmeticException: long overflow




See Also