Java Math class provides addExact method, which take two integer /or long arguments and return the sum of its arguments, throw an exception if the result overflows an int or long.
Signature
public static int addExact(int x, int y)
Returns the sum of its arguments, throwing an exception if the result overflows an int.
public static long addExact(long x, long y)
Returns the sum of its arguments, throwing an exception if the result overflows a long.
Find the below working application.
AddExactDemo.java
package com.sample.app;
public class AddExactDemo {
public static void main(String[] args) {
System.out.println("Math.addExact(10, 20) : " + Math.addExact(10, 20));
System.out.println("Math.addExact(10l, 20l) : " + Math.addExact(10l, 20l) +"\n");
int a = Integer.MAX_VALUE;
int b = 10;
try {
System.out.println("Math.addExact(" + a + ", " + b + ") : ");
Math.addExact(a, b);
} catch (ArithmeticException e) {
e.printStackTrace();
}
System.out.println();
long c = Long.MAX_VALUE;
long d = 10l;
try {
System.out.println("Math.addExact(" + c + ", " + d + ") : ");
Math.addExact(c, d);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output
Math.addExact(10, 20) : 30 Math.addExact(10l, 20l) : 30 Math.addExact(2147483647, 10) : java.lang.ArithmeticException: integer overflow at java.lang.Math.addExact(Math.java:790) at com.sample.app.AddExactDemo.main(AddExactDemo.java:15) Math.addExact(9223372036854775807, 10) : java.lang.ArithmeticException: long overflow at java.lang.Math.addExact(Math.java:809) at com.sample.app.AddExactDemo.main(AddExactDemo.java:27)
Previous Next Home
No comments:
Post a Comment