Skip to content

Instantly share code, notes, and snippets.

@huskercane
Created June 5, 2018 14:02
Show Gist options
  • Save huskercane/9441def2f3441271080edaadf1e48805 to your computer and use it in GitHub Desktop.
Save huskercane/9441def2f3441271080edaadf1e48805 to your computer and use it in GitHub Desktop.
safe addition in java - not to overflow
public class X {
public static final int safeAdd(int left, int right){
if (right > 0? left > Integer.MAX_VALUE - right: left < Integer.MIN_VALUE - right) {
// throw new ArithmeticException("Integer overflow");
}
return (left + right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment